天天看點

Linq嵌套分組執行個體

1 建立控制台應用程式GroupByExp,準備示例資料。

public class ExampleModel
{
    public int C1 { get; set; }//列1
    public string C2 { get; set; }//列2
}
List<ExampleModel> listExampleModel = new List<ExampleModel>();
listExampleModel.Add(new ExampleModel() { C1 = 1, C2 = "b"});
listExampleModel.Add(new ExampleModel() { C1 = 1, C2 = "a"});
listExampleModel.Add(new ExampleModel() { C1 = 2, C2 = "a"});
listExampleModel.Add(new ExampleModel() { C1 = 2, C2 = "a"});
listExampleModel.Add(new ExampleModel() { C1 = 3, C2 = "c"});
listExampleModel.Add(new ExampleModel() { C1 = 4, C2 = "a"});
           

2 嵌套分組實作

通過Linq實作嵌套分組,分組包含兩步:

(1)按照C1進行分組(得到下圖左半部效果)

(2)再按照C2進行分組(得到下圖右半部效果)

Linq嵌套分組執行個體

下面給出嵌套分組及結果輸出的代碼。

var exampleModelGroup = listExampleModel.GroupBy(it => it.C1).GroupBy(it => it.First().C2);
List<ExampleModel> listResult = new List<ExampleModel>();
foreach (var group1 in exampleModelGroup)
{
     foreach (var group2 in group1)
     {
          listResult.AddRange(group2.ToList());
     }
}
foreach(var exampleModel in listResult)
{
     Console.WriteLine("{ C1 = " + exampleModel.C1 + ", C2 = " + exampleModel.C2 + " }");
}
           

執行結果如下圖所示。

Linq嵌套分組執行個體

3 分析說明

分組及結果輸出的詳細過程如下圖所示。

Linq嵌套分組執行個體

嵌套分組操作中,我們要想擷取最終分組中的成員資訊的話,可以按照本文所述方法完成,本質上就是周遊。