5

一般的なListmyListに対して作業グループBy句とSortBy句を作成するのに苦労しています。myListには、プロパティ「設定」のリストがあり、それ自体に各ビジネスの「子」プロパティのリストが含まれています。

業界ごとにグループ化し、各業界内で会社名で並べ替えたいと思います。私の意図はこれです:

string groupSetting = "Industry";
sortSetting = "BusinessName";
myList.GroupBy(p => p.Settings.Find(s => s.Name == groupSetting)).OrderBy(p => p.Settings.Find(t => t.Name == sortSetting));

ただし、次のエラーが発生します:' System.Linq.IGroupingには設定の定義が含まれておらず、System.Linq.Igrouping型の最初の引数を受け入れる拡張メソッドSettingsが見つかりませんでした...'注文を呼び出すことができないことを示しますいくつかの変換または追加の処理なしの句による。

私はこれを分割して機能させるためにさまざまなことを試みましたが、何かが欠けています。助けていただければ幸いです

4

1 に答える 1

13

問題はGroupBy、設定の単一のリストを返さず、「リストのリスト」を返すことです。これはIGroupingあなたが見ているものです。

IGrouping内の各グループを反復処理し、そのグループを並べ替えてから、グループ内の各アイテムを反復処理する必要があります。観察:

public static void Main( string[] args )
{
    var groupSetting = "Industry";

    // step 1: group the data. Note this doesn't actually create copies of the data as
    // it's all lazy loaded
    // BEWARE. If a company doesn't have the "Industry" setting, this will throw an exception
    var grouped = companies.GroupBy(c => c.Settings.First(s => s.Name == groupSetting).Value);
    foreach( var group in grouped )
    {
        Console.WriteLine(group.Key);// this is the Value that came out of the GroupBy

        // Note how we have to do the ordering within each individual group. 
        // It doesn't make sense to try group them in one hit like in your question
        foreach( var item in group.OrderBy(bus => bus.Name) )
            Console.WriteLine(" - " + item.Name);
    }
}

明確にするために提供されたデータ構造:

struct Setting { public string Name; public string Value; }
struct Business { public string Name; public IEnumerable<Setting> Settings; }

static IEnumerable<Business> companies = new[]{
    new Business{ Name = "XYZ Inc.", Settings = new[]{ 
        new Setting{ Name="Age", Value="27"},
        new Setting{ Name="Industry", Value="IT"}
    }},
    new Business{ Name = "Programmers++", Settings = new[]{ 
        new Setting{ Name="Age", Value="27"},
        new Setting{ Name="Industry", Value="IT"}
    }},
    new Business{ Name = "Jeff's Luxury Salmon", Settings = new[]{ 
        new Setting{ Name="Age", Value="63"},
        new Setting{ Name="Industry", Value="Sports"}
    }},
    new Business{ Name = "Bank of Khazakstan", Settings = new[]{ 
        new Setting{ Name="Age", Value="30"},
        new Setting{ Name="Industry", Value="Finance"}
    }},
};

これにより、次の出力が生成されます。コードをコピーして貼り付け、実行して再生します。

IT
 - Programmers++
 - XYZ Inc.
Sports
 - Jeff's Luxury Salmon
Finance
 - Bank of Khazakstan
于 2009-05-19T04:25:41.393 に答える