13

我必须查询这张表:

symbol    time
------    ----------
aaa       2013-04-18 09:10:28.000    
bbb       2013-04-18 09:10:27.000    
aaa       2013-04-18 09:10:27.000    
bbb       2013-04-18 09:10:26.000

对于具有最大时间值的所有不同符号,我需要一行。我如何编写我的 linq 查询?

提前致谢,

4

4 回答 4

21

按符号对行进行分组,然后从每个组项中选择最大时间Table是上下文中的数据库表名):

from r in Table
group r by r.symbol into g
select g.OrderByDescending(x => x.time).First()

与方法语法相同:

Table.GroupBy(r => r.symbol)
     .Select(g => g.OrderByDescending(x => x.time).First());
于 2013-04-18T07:22:50.593 回答
9

试试这个

var q = MyTable.GroupBy(x => x.symbol )
               .Select(g => g.OrderByDescending(i => i.time).First());

或像这样使用 max

 var data = from r in MyTable
                   group r by r.symbol into g
                   select new { name= g.Key, data= g.Max(a=>a.time) };
于 2013-04-18T07:24:43.530 回答
3

我实际上会使用。

void Main()
{
    var set = new [] {
        new Foo{A = "aaa", B = 1},
        new Foo{A = "bbb", B = 2},
        new Foo{A = "aaa", B = 3},
        new Foo{A = "bbb", B = 4},
    };

    var result = from x in set
                group x.B by x.A into g
                select new {id = g.Key, biggest = g.Max()};

    Console.WriteLine(result);
}
于 2013-04-18T07:50:30.407 回答
0

你可以在 Linq 中使用 lambda 表达式 -

var result= (from li in List.Distinct().OrderByDescending(x => x.time)
                       select li).FirstOrDefault();
于 2013-04-18T13:16:03.693 回答