检查列表< List< int> []>.包含使用Linq的值 [英] Check a List<List<int>[]> contains a value using Linq

查看:43
本文介绍了检查列表< List< int> []>.包含使用Linq的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 List< List< int> []> ,其中包含列表项,例如

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

我想检查c中包含的任何数组的值是否为2.这或多或少是对还是错.

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.

到目前为止,我可以使用Linq代码检查a或b是否包含2

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

将此扩展到c

var result=c.Any(p=> p.Select(value => value.Contains(2)).First());

//上面的代码p => p.Select(value => value.Contains(2))返回一个Enumerable,我取第一个.我不太肯定这是使用linq解决此问题的正确方法.有更好的方法吗?

// 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?

推荐答案

如果您知道如何在单个列表中进行搜索,则应该能够以完全相同的方式在列表中进行搜索.只需使用 SelectMany 并使用相同的条件.

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

然后是列表列表:

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

这篇关于检查列表&lt; List&lt; int&gt; []&gt;.包含使用Linq的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆