本文介绍了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的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 04:00