在linq中进行分组和枚举

时间:2015-12-29 23:42:36

标签: c# linq

对不起,我怎么能在linq中得到这个结果?一些提示?

List<Test> listTests = new List<Test>();

var item1 = new Test() { NumberFac = 915170958, Description = "aa" };

var item2 = new Test() { NumberFac = 915170956, Description = "bb" };

var item3 = new Test() { NumberFac = 915176287, Description = "cc" };

var item4 = new Test() { NumberFac = 915170956, Description = "dd" };

var item5 = new Test() { NumberFac = 915176287, Description = "aa" };

var item6 = new Test() { NumberFac = 915170958, Description = "mm" };

var item7 = new Test() { NumberFac = 915176287, Description = "ll" };

listTests.Add(item1);

listTests.Add(item2);

listTests.Add(item3);

listTests.Add(item4);

listTests.Add(item5);

listTests.Add(item6);

listTests.Add(item7);

结果

 #Num |NumberFac|Description

   1   |915170958| aa

   2   |915170958| mm

   1   |915170956| bb

   2   |915170956| dd

   1   |915176287| cc

   2   | 915176287| aa

   3   |915176287 | ll  

1 个答案:

答案 0 :(得分:1)

你去吧

var result = listTests
    .GroupBy(e => e.NumberFac)
    .SelectMany(g => g.Select((e, i) => new { Num = i + 1, e.NumberFac, e.Description }))
    .ToList();

首先,GroupBy用于按NumberFac对项目进行分组,然后用SelectMany对结果进行分组,并使用Select的特殊重载来提供元素索引以生成小组内#Num