LINQ-编写具有不同和orderby的查询 [英] LINQ - writing a query with distinct and orderby

查看:82
本文介绍了LINQ-编写具有不同和orderby的查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对LINQ很陌生.

假设我有下表:

Incident 

ID DeviceID Time          Info

1    1      5/2/2009    d

2    2      5/3/2009    c

3    2      5/4/2009    b

4    1      5/5/2009    a

在LINQ中,如何编写查询以查找最新的和不同的(在设备ID上)事件集?我想要的结果是这样的:

In LINQ, how could I write a query that finds the most recent and distinct (on Device ID) set of incidents? The result I'd like is this:

ID DeviceID Time           Info

3    2      5/4/2009    b

4    1      5/5/2009    a

您必须创建IEqualityComparer来做到这一点吗?

Do you have to create an IEqualityComparer to do this?

推荐答案

您可以使用以下方法获取每个设备的最新事件(这是我对您问题的理解):

You can get the most recent incidents for each device (this is how I understood your question) with:

var query = 
   incidents.GroupBy(incident => incident.DeviceID)
            .Select(g => g.OrderByDescending(incident => incident.Time).First())
            .OrderBy(i => i.Time); // only add if you need results sorted

这篇关于LINQ-编写具有不同和orderby的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆