开发者

Use Linq to filter on distinct options and newest date

开发者 https://www.devze.com 2023-01-28 17:06 出处:网络
I have an object, Activity.On Activity, the开发者_如何学编程 user can select a Frequency, a drop down list with ~10 different options.I already have a method to return all the Activities for a given u

I have an object, Activity. On Activity, the开发者_如何学编程 user can select a Frequency, a drop down list with ~10 different options. I already have a method to return all the Activities for a given user, but I would like to take it further and use Linq to filter my List to only the latest of each Frequency for an activity.

For example, if the user has 3 Activities:

Activity 1, 12/4/2010, weekly
Activity 2, 12/1/2010, daily
Activity 3, 12/2/2010, weekly

I would like to limit my List of Activities to only Activity 1 and 2


List<Activity> activities = //whatever
var latestActivities = activities
    .GroupBy(a => a.Frequency)
    .Select(grp => grp.OrderByDescending(a => a.Date).First());
0

精彩评论

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