mahboub_mo
mahboub_mo

Reputation: 3038

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?

Upvotes: 15

Views: 72367

Answers (3)

Ivan Marijanović
Ivan Marijanović

Reputation: 1

I have similar issue:

This is code:

List<string> mds = _userService.GetAllMDUsers();
conf = _context.BillingsConfirmationsView.Where(c=> mds.Contains(c.EmployeeShort.ToUpper()));

I am having issue with following situation. Let say I have employee with short "js" and in my mds List I have another employee with short jsc. Now I get back records for both employees and I should get only for jsc since js is not memeber of mds. Now I understand that this is because "js" is subset of "jsc" but dont know how to get correct result. EmployeeShort is string in BillingsConfirmationsView model.

Ivan

Upvotes: 0

Yaugen Vlasau
Yaugen Vlasau

Reputation: 2218

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

Upvotes: 4

Ahmed KRAIEM
Ahmed KRAIEM

Reputation: 10427

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

Upvotes: 22

Related Questions