Linq - How to select items from a list that contains only items of another list?

c# entity-framework linq

Question

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?

1
13
6/25/2013 12:53:57 PM

Accepted Answer

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)));
18
6/25/2013 1:04:26 PM

Popular Answer

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))


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow