Linq使用FirstOrDefault

时间:2015-11-30 10:40:41

标签: asp.net-mvc entity-framework linq

我尝试在2列上对Linq查询进行排序:seq和version:

表格

id | seq | version
01 | 1   | 1
02 | 1   | 2
03 | 1   | 1
04 | 2   | 2
05 | 2   | 3
06 | 3   | 1

我的查询:

  var events = from x in db.Events
                         group x by x.Seq into s
                         select s.OrderBy(z => z.Seq).OrderByDescending(z => z.version).FirstOrDefault();

当前结果:

id | seq | version
05 | 2   | 3
06 | 3   | 1
02 | 1   | 2

期望的结果:

id | seq | version
02 | 1   | 2
05 | 2   | 3
06 | 3   | 1

问题似乎是组合或2 orderby和FirstOrDefault()。解决此问题的正确查询是什么?

2 个答案:

答案 0 :(得分:2)

已修复

var events = (from x in db.Events
           group x by x.Seq into s
           select s.OrderByDescending(z => z.version).FirstOrDefault()).OrderBy(z => z.Seq);

见工作Fiddle

答案 1 :(得分:1)

正确的方法是首先按seq进行分组,然后按version排序并获取所需的单个结果,最后按seq对结果集进行排序,如下所示

var events = data
    .GroupBy(x => x.seq, (key, items) => items.OrderByDescending(x => x.version).FirstOrDefault())
    .OrderBy(x => x.seq);