Reputation: 942
Suppose I have the following collection:
ONE
- Banana
- Mango
TWO
- Apple
- Mango
THREE
- Orange
- Pear
I want to get only the collection which has Mango in it, such as:
ONE
- Banana
- Mango
TWO
- Apple
- Mango
The following example still returns a collection with 3 items:
List<Order> list = new List<Order> {
new Order { Id = 1, Name = "ONE", Items = new List<Items> { new Items { Id = 1, Nama = "Banana" }, new Items { Id = 2, Nama = "Mango" } }},
new Order { Id = 1, Name = "TWO", Items = new List<Items> { new Items { Id = 1, Nama = "Orange" }, new Items { Id = 2, Nama = "Mango" } }},
new Order { Id = 1, Name = "THREE", Items = new List<Items> { new Items { Id = 1, Nama = "Pear" }, new Items { Id = 2, Nama = "Chery" } }},
};
var result = list.Where(x => x.Items.Any(y => !y.Nama.Equals("Mango"))).ToList();
Upvotes: 0
Views: 44
Reputation: 556
You're almost there! Try reading out the logic of your code to make sense of what it's is doing.
Your inner Where clause logic is saying 'Check the List and if Any of the entries does not Equal "Mango", then we keep that list'. With this logic, every entry in your list has a List with an entry that does not equal "Mango".
Reverse your logic so it says 'Check the List and if Any of the entries Equals "Mango", then we keep that list'.
var result = list.Where(x => x.Items.Any(y => y.Nama.Equals("Mango"))).ToList();
Upvotes: 1
Reputation: 1216
You are getting all collections where there is at least one item that is not Mango. Try removing the "!".
var result = list.Where(x => x.Items.Any(y => y.Nama.Equals("Mango"))).ToList();
Upvotes: 1