Reputation: 599
I have a List<List<int>[]>
containing lists items e.g
List<int> a= new List<int>(){ 2, 2, 3, 4, 5};
List<int> b= new List<int>() { 2, 2, 2, 6 };
List<List<int>[]> c = new List<List<int>[]>();
c.Add(new[]{a,b});
I want to check if any of the arrays contained in c have 2 as a value . This is more or less a true or false answer.
So far I can check if a or b contains 2 using the Linq code
var result = a.Any(p=> p==2); // this outputs 2
extending this to the c
var result=c.Any(p=> p.Select(value => value.Contains(2)).First());
// the above code p=> p.Select(value => value.Contains(2)) returns an Enumerable and I take the first one. I'm not positive this is the right way to go about this problem using linq. Is there a better way of doing this?
Upvotes: 1
Views: 11065
Reputation: 103485
c.SelectMany(inner=>inner.SelectMany (i =>i )).Contains(2).Dump();
Upvotes: 0
Reputation: 22866
I love PetSerAl's any any any answer but a tiny change
c.Any(x => x.Any(y => y.Contains(2)))
Upvotes: 2
Reputation: 205539
If you know how to search in a single list, you should be able to search in list of lists exactly the same way. Just flatten it with SelectMany
and use the same criteria.
For your case, if this is for single list:
var result = a.Any(p => p == 2);
then for list of lists it would be:
var result = c.SelectMany(x => x).Any(p => p == 2);
and similar for third level as in your example:
var result = c.SelectMany(x => x).SelectMany(x => x).Any(p => p == 2);
Upvotes: 10
Reputation: 9510
List<int> a = new List<int>() { 2, 2, 3, 4, 5 };
List<int> b = new List<int>() { 2, 2, 2, 6 };
List<List<int>[]> c = new List<List<int>[]>();
c.Add(new[] { a, b });
//Lambda
bool IsValueExists = c.Any(i => i != null && i.Any(i1 => i1.Any(i2=>i2 == 2)));
//OR
//Linq
bool IsValueExists = (from i in c
from i1 in i
from i2 in i1
where i2 == 2
select i2).Any();
Upvotes: 0