我需要从 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();