简体   繁体   English

展平Linq Group查询

[英]Flattening Linq Group query

I have a list of data like so: 我有一个像这样的数据列表:

ID AddressPurpose Address ...
1  L
1  P
2  L
2  P
3  P
3  L
4  P
4  L
5  P
6  L

I want to be able to filter the data so that for each unique number if there is a P row then it is returned else the L row is returned. 我希望能够过滤数据,以便对于每个唯一的数字,如果有一个P行,则返回它,否则返回L行。 So the data will look like this: 所以数据看起来像这样:

ID AddressPurpose Address ...
1  P
2  P
3  P
4  P
5  P
6  L

At the moment I have this query which works fine: 目前我有这个查询工作正常:

var query = from c in list
            orderby c.AddressPurpose descending
            group c by c.ID
            into g
                select g;

var finalList = new List<Company>();
foreach (var list in query)
{
    finalList.Add(list.First());
}
return finalList;

Is there a better way to do this without using the extra foreach? 没有使用额外的foreach,有没有更好的方法来做到这一点?

You could always nest your queries: 您可以始终嵌套查询:

var query =
    from i in (
        from c in list 
        orderby c.AddressPurpose descending 
        group c by c.ID into g 
        select g)
    select i.First();

return query;

I'm sure this isn't the only way to do it (or possibly even the best), but it does wrap your "foreach" up into the one query. 我确信这不是唯一的方法(或者甚至可能是最好的方式),但它确实将你的“foreach”包装到一个查询中。

Edit 编辑

In fact, you can simplify this down to: 实际上,您可以将其简化为:

var query = from c in list
            orderby c.AddressPurpose descending
            group c by c.ID into g
            select g.First();

That seems to give the right result. 这似乎给出了正确的结果。

为什么不select g.First()呢?

var finalList = list
  .GroupBy(c => c.ID)
  .Select(g => g.OrderByDescending(c => c.AddressPurpose).First())
  .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM