Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 217
mahboub_mo Avatar asked Jun 25 '13 12:06

mahboub_mo


People also ask

What is the difference between the Select clause and SelectMany () method in LINQ?

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.

What is let clause in LINQ?

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.

What does SelectMany do in LINQ?

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.


2 Answers

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)));
like image 125
Ahmed KRAIEM Avatar answered Sep 17 '22 17:09

Ahmed KRAIEM


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))
like image 20
Yaugen Vlasau Avatar answered Sep 21 '22 17:09

Yaugen Vlasau