linq从一组返回单行

时间:2009-11-23 23:07:26

标签: c# linq

我有一个这样的行列表(因为我使用的是DefaultIfEmpty,所以是NULL)

Vol           Component         Dwg      View    Revision   

Volume U01  Composed Drawings   SJTest  1   B
Volume U01  Composed Drawings   SJTest  1   A
Volume U01  Composed Drawings   SJTest  1   NULL
Volume U03  Composed Drawings   SJTest2 2   NULL

我想按每个组的最后一个coln(A,B,NULL)排序,然后只得到第一行。所以在这种情况下,我应该将最终设置为:

Volume U01  Composed Drawings   SJTest  1   B
Volume U03  Composed Drawings   SJTest2 2   NULL

有什么想法?我迷失了如何从分组中获得这一点 - 每组的第一行。

这是LINQ-SQL ...对不起忘了。

感谢 苏尼特

1 个答案:

答案 0 :(得分:1)

因为你说第一组的第一行应该是修订版“B”,我猜你想按降序排序,所以这样的事情呢?

var query = yourData
            .GroupBy(x => new { x.Vol, x.Component, x.Dwg, x.View })
            .Select(g => g.OrderByDescending(x => x.Revision).First());

// and to test...
foreach (var x in query)
{
    Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}",
        x.Vol, x.Component, x.Dwg, x.View, x.Revision ?? "NULL");
}

// Volume U01    Composed Drawings    SJTest     1    B
// Volume U03    Composed Drawings    SJTest2    2    NULL