【问题标题】:linq return single row from a gouplinq 从组中返回单行
【发布时间】:2009-11-24 08:05:48
【问题描述】:

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

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

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

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

有什么想法吗?我不知道如何从分组中得到这个 - 每个组的第一行。

这是 LINQ-SQL...抱歉忘记了。

谢谢 苏尼特

【问题讨论】:

  • 这是 Linq-to-SQL 还是内存中的 Linq?您能否发布您已经拥有的代码的一小部分(相关)摘录,以便我们可以将其用作起点?
  • 你有任何代码可以发布吗?

标签: c# linq


【解决方案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

【讨论】:

  • 这适用于一个小的编辑: .GroupBy(x=>new {x.Volumne, x.Component, x.Drawing}, x=>x) .Select(g=>g.First ());
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多