开发者

LINQ group by and getting latest value

开发者 https://www.devze.com 2022-12-27 18:19 出处:网络
Say I have a structure like: class SomeObject Public Name as String Public Created as Date ... end class I have a List(of SomeObject), which has mu开发者_开发知识库ltiple entries for each name with

Say I have a structure like:

class SomeObject
   Public Name as String
   Public Created as Date
   ...
end class

I have a List(of SomeObject), which has mu开发者_开发知识库ltiple entries for each name with different times. I'd like to select the newest (largest Created value) object for each Name.

Given:

Name   Created
A      2010-04-16     *
A      2010-04-15
B      2010-04-12
B      2010-04-13     *
C      2010-04-16     *

I'd like to pick the objects with the * beside them.

Is this possible using LINQ?


It is:

var maxObjects =
    from o in myList
    group o by o.Name into g
    select new { Name = g.Key, Created = g.Max(o => o.Created) };

See 101 Linq samples to see how Linq can be used.

0

精彩评论

暂无评论...
验证码 换一张
取 消