[英]LINQ to select a column with max date from a group
I have following table in which I can have multiple time stamps for a single name. 我有一张下表,其中一个名字可以有多个时间戳。 I want to get the name (distinct) with max time stamp. 我想获得带有最大时间戳的名称(不同)。
Id Name TimeStamp
66 Name1 19/10/2017
67 Name1 20/10/2017
68 Name1 21/10/2017
69 Name2 19/10/2017
70 Name2 20/10/2017
71 Name2 21/10/2017
72 Name2 22/10/2017
73 Name3 19/10/2017
74 Name3 20/10/2017
75 Name3 21/10/2017
I am able to do group by,now need to select the element with max value from that group. 我能够进行分组,现在需要从该分组中选择具有最大值的元素。
var tempResult = data.GroupBy(x => x.Name);
I tried doing this , nut it only selected the date time, but I need the complete item: 我尝试这样做,但它只选择了日期时间,但是我需要完整的项目:
foreach (var item in tempResult)
{
var maxItem = item.Max(x=>x.StartTime);
}
var result = from d in data
group d by d.Name into g
select new { Name = g.Key, MaxDate = g.Max(s => s.StartTime) }
Or if you do not like query syntax then: 或者,如果您不喜欢查询语法,则:
data.GroupBy(i => i.Name).Select(g => new
{
Name = g.Key,
MaxDate = g.Max(row => row.StartTime)
});
@CodingYoshi's answer is enough if you just need Name and TimeStamp. 如果您只需要Name和TimeStamp,@ CodingYoshi的答案就足够了。 If you want to select all other properties (full object) you can use this. 如果要选择所有其他属性(完整对象),则可以使用此属性。
var tempResult = data.GroupBy(x => x.Name)
.Select(g => g.OrderByDescending(y => y.TimeStamp).FirstOrDefault());
if you like query form then this 如果您喜欢查询表格,那么这
var tempResult2 = from x in data
group x by x.Name into g
select g.OrderByDescending(y => y.TimeStamp).FirstOrDefault();
Here in your case you can access all the properties (including ID). 在这种情况下,您可以访问所有属性(包括ID)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.