如何从项目列表中找到最小日期?

时间:2015-06-14 21:24:25

标签: c# linq

我有一个像这样的表结构

id  |  itemId |  date |
1   |  a1     | 6/14/2015
2   |  a1     | 3/14/2015
3   |  a1     | 2/14/2015
4   |  b1     | 6/14/2015
5   |  c1     | 6/14/2015

从这个表格结构中,我试图获得具有最小日期的所有不同项目。例如我想获得id = 3,4和5.

我尝试过以下代码,但我无法

var items = (from i in _db.Items
             //where min(i.date) // doesn't seem right
             group i by i.itemID
             into d select new
             {
                 iId = d.Key,
             }).Distinct();

2 个答案:

答案 0 :(得分:0)

根据您的样本数据,我会这样做:

var query =
    from i in _db.Items
    group i by i.itemId into gis
    let lookup = gis.ToLookup(x => x.date, x => x.id)
    from x in lookup[gis.Min(y => y.date)]
    select x;

答案 1 :(得分:-1)

var items = from i in _db.Items
            group i.date by i.itemID
            into d select new {
                iId = d.Key, iDate = d.Min()
            };