Check a List<List<int>[]> contains a value using Linq

核能气质少年 提交于 2021-02-04 16:42:22

问题


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?


回答1:


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



回答2:


I love PetSerAl's any any any answer but a tiny change

c.Any(x => x.Any(y => y.Contains(2)))



回答3:


you need something like this:

c.Where(i=>i.Any(x=>x.Contains(2)))



回答4:


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



回答5:


c.SelectMany(inner=>inner.SelectMany (i =>i )).Contains(2).Dump();


来源:https://stackoverflow.com/questions/38401836/check-a-listlistint-contains-a-value-using-linq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!