-2

我需要从 DataCop 日期时间字段中按名称字段和最大值选择不同,此代码不起作用,谢谢

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();
4

2 回答 2

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();
于 2013-02-07T09:35:38.613 回答
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
           };
于 2013-02-07T09:30:52.473 回答