简体   繁体   English

使用LINQ获取具有完全相同值的所有属性?

[英]Using LINQ to get all property with the exact same value?

I have a list of data like this: 我有这样的数据列表:

Prod1: Id=1,  Name="Book",    Active=true
Prod2: Id=2,  Name="Book",    Active=false
Prod3: Id=3,  Name="Book",    Active=true
Prod4: Id=4,  Name="Laptop",  Active=true
Prod5: Id=5,  Name="Laptop",  Active=true
Prod6: Id=6,  Name="Laptop",  Active=true

What I want to perform is to get reduced list like this: 我想要执行的是获得这样的简化列表:

Prod1: Id=4, Name="Laptop", Active=true

What I am trying to do is that I need to select all products group by its Name, and return all that has true. 我想要做的是我需要按名称选择所有产品组,并返回所有真实的产品。 Since Book has one false, it should not return Book. 由于Book有一个假,它不应该返回Book。

I've tried this one: 我试过这个:

lstProducts = lstProducts 
                .Where(x =>
                    lstProducts 
                   .All(c => c.Name == x.Name && c.Active == true))
                .GroupBy(c => c.Name).Select(c => c.First())
                .ToList();

But its returning zero results. 但它的归零结果。 If I do a where clause where Active == true , its getting a Book product, which shouldn't since all of its Active should be true in order to get it. 如果我在一个where clause where Active == true ,它会得到一个Book产品,因为它的所有Active都应该为true才能得到它。

What you are looking for is to first group all items by their Name , then filter only those that have all true for Active and last retrieve the first item for each group: 您要查找的是首先按Name对所有项目进行分组,然后仅过滤那些对于Active都具有true的项目,并最后检索每个组的第一项:

var result = lstProducts.GroupBy(item => item.Name)
                        .Where(group => group.All(item => item.Active)
                        .Select(group => group.First());

If you want to ensure some ordering for the group, as in your example then: 如果您想确保该组的某些排序,如您的示例所示:

var result = lstProducts.GroupBy(item => item.Name)
                        .Where(group => group.All(item => item.Active)
                        .Select(group => group.OrderBy(item => item.Id).First());

Group first, then filter: 先分组,然后过滤:

lstProducts
    .GroupBy(c => c.Name)
    .Where(g => g.All(c => c.Active))
    .Select(g => g.First())
    .ToList()

GroupBy guarantees that items within groups have the same order with respect to each other as they did before the grouping. GroupBy保证组内的项目在分组之前具有相同的顺序。 If you'd like to choose the element with the minimum id to represent the group and your original list isn't ordered by id, however, you can use Min instead of First : 如果您想选择具有最小id的元素来表示组,并且您的原始列表不是按ID排序,则可以使用Min而不是First

lstProducts
    .GroupBy(c => c.Name)
    .Where(g => g.All(c => c.Active))
    .Select(g => g.Min(c => c.Id))
    .ToList()

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

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