1

我有一个清单:

class test
{
    name,
    timestamp
}

我想获得所有具有相同名称的最后(最新)测试。许多测试具有相同的时间戳。

例如:

name1, 2012-10-25 3:00PM
name1, 2012-10-25 3:00PM
name2, 2012-10-25 3:05PM
name2, 2012-10-25 3:05PM
name1, 2012-10-25 3:10PM
name1, 2012-10-25 3:10PM
name2, 2012-10-25 3:15PM
name2, 2012-10-25 3:15PM

我只需要获取每个名称的最后测试:

name1, 2012-10-25 3:10PM
name1, 2012-10-25 3:10PM
name2, 2012-10-25 3:15PM
name2, 2012-10-25 3:15PM
4

2 回答 2

1
var groups = list.GroupBy(x => x.name)
                 .Select(x => new  test{ 
                    Name = x.Key, 
                    TimeStamp = x.Max(y => y.timestamp) 
                  })
                 .ToList();
于 2012-10-25T17:13:48.010 回答
0

试试这个:

var q = from l in list
        group l by l.Name into g
        select new
        {
            Name = g.Key,
            Max = g.Max (x => x.Timestamp)
        } into x
        from y in list 
        where x.Name == y.Name && x.Max == y.Timestamp
        select y;

这里发生的首先是对listby进行分组Name,然后我为每个组选择 max Timestamp。这去into x。然后我将它重新加入list到分组中,匹配分组中的所有对,这样我就选择了与分组项目匹配的所有原始项目。

于 2012-10-25T18:12:31.140 回答