Alan B
Alan B

Reputation: 2289

Linq to check if all value from another list exist

I have list of values as below

List 1

--
Id Country market

1   AU       2

2   NZ       2

3   GB       3

4   GG       3

I have another list which is as below

List 2

location country

2         AU

2         NZ

3         GB

3         IR

I would like to pull the location from list 2 where country satisfies in List 1 and by market. which means I need to pull "2" as location from List 2 for market = 2 because location 2 satisfy the values ( which are AU and NZ) whereas location 3 failed the validation because not all the countries (from list 1) are in list 2.

I would like to know if we can write this in LINQ statement. I can write using loop to find out each matching criteria but I am thinking of easier and better way of writing this in LINQ.

Upvotes: 0

Views: 539

Answers (1)

Hari Prasad
Hari Prasad

Reputation: 16956

If you only interested in knowing all List1 entries exists in List2 then you could do this.

bool allexist = list1.All(l=> list2.Any(x=> x.location == l.market && x.Country == l.Country));

or, if you would like to know all List1 entries exists in List2 then this

var existsinBoth = list1.Where(l=> list2.Any(x=> x.location == l.market && x.Country == l.Country));

Upvotes: 2

Related Questions