Using LINQ, can I get all properties with the same value?

I have a list of such data:

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

I want to do the following:

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

What I'm trying to do is that I need to select the entire group of products by name and return everything that has true. Since the book has one false, it should not return the book.

I 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 the result of his return is zero. If I do where clause where Active == true, then he receives a Book product, which should not, since all of his Active must be true in order to receive them.

+4
source share
2 answers

Name, , true Active, :

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

, , :

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

, :

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

GroupBy , , . youd id , id, Min First:

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

Source: https://habr.com/ru/post/1683790/


All Articles