I have this two classes:
public class Item
{
public int Id{get;set;}
public List<Test> TestList{get;set;}
}
public class Test
{
public int Id{get;set;}
public Item Item{get;set;}
public byte State{get;set;}
}
Item Class Data:
Id
1
2
3
And Test Class Data:
Item State
1 1
1 2
1 3
2 1
2 4
3 2
Now i need to write a query that select the Items from my class that just have state of 1 and 2.For example for the sample above it should returns row with Item=3. i wrote this query:
var stateList=new List<byte>(){1,2};
Items.Where(x => x.TestList.Select(c => c.State).Any(s => stateList.Contains(s)));
but it returns Item=1 either.Any Idea?
Select and SelectMany are projection operators. A select operator is used to select value from a collection and SelectMany operator is used to selecting values from a collection of collection i.e. nested collection.
The Let keyword allows you to create a range variable and initialized with the result of the query expression and then you are allowed to use that variable with the upcoming clause in the same query.
The SelectMany in LINQ is used to project each element of a sequence to an IEnumerable<T> and then flatten the resulting sequences into one sequence. That means the SelectMany operator combines the records from a sequence of results and then converts it into one result.
This returns the items which all states are in stateList
, I think that that's what you need:
Items.Where(x => x.TestList.All(s => stateList.Contains(s.State)));
in case you need only those items which TestList have only items with status 2:
tems.Where( i => i.TestList.All(li => li.State == 2))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With