与另一列linq相区别一列和最大值

时间:2013-02-07 09:27:47

标签: c# linq distinct

我需要从Name字段中选择distinct,从DataCop datetime字段中选择max, 这段代码不起作用,谢谢

List<Data> l = new List<Data>();
l.Add(new Data { Id = 0, Name = "A", DataCop = new DateTime(2012, 1, 4) });
l.Add(new Data { Id = 1, Name = "A", DataCop = new DateTime(2012, 1, 5) });
l.Add(new Data { Id = 2, Name = "A", DataCop = new DateTime(2012, 5, 4) });
l.Add(new Data { Id = 3, Name = "B", DataCop = new DateTime(2012, 3, 1) });
l.Add(new Data { Id = 4, Name = "B", DataCop = new DateTime(2012, 3, 5) });
l.Add(new Data { Id = 5, Name = "C", DataCop = new DateTime(2012, 2, 1) });
l.Add(new Data { Id = 6, Name = "D", DataCop = new DateTime(2012, 2, 1) });

DateTime start = new DateTime(2012,1,2);
DateTime end = new DateTime(2012,4,1);


var res = (from Data d in l
           let max = l.Where(x => x.Id == d.Id).Max(x => x.DataCop)
           let maxId = l.Where(x => x.Id == d.Id && x.DataCop == max)
                        .Select(x => x.Id).FirstOrDefault()
           where d.DataCop >= start && d.DataCop <= end &&
               d.Id == maxId && d.DataCop == max
           select d).ToList();


foreach (var item in res)
{
    Console.WriteLine(item.Id.ToString() + "\t" + item.Name + "\t" + item.DataCop.ToShortDateString());
}
Console.ReadLine();

2 个答案:

答案 0 :(得分:2)

使用linq方法语法

按名称分组并选择按DataCop降序排序的每个组的第一个项目(数据实例)(这将把最大日期放在第一位)

var res = l.GroupBy(m => m.Name)
            .Select(g => g.OrderByDescending(x => x.DataCop)
                        .First())
            .ToList();

使用查询语法(混合)

var result = (from r in l
              group r by r.Name into g
              select g.OrderByDescending(x => x.DataCop)
                      .First())
             .ToList();

答案 1 :(得分:0)

按名称分组数据,然后从每个组中选择最后一个数据:

 var res = from d in l
           group d by d.Name into g
           let lastData = g.OrderByDescending(x => x.DataCop).First()
           select new Data()
           {
               Name = g.Key,
               Id = lastData.Id,
               DataCop = lastData.DataCop
           };