检查是否 list<t>包含任何其他列表 [英] Check if list&lt;t&gt; contains any of another list

查看:32
本文介绍了检查是否 list<t>包含任何其他列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的参数列表:

I have a list of parameters like this:

public class parameter
{
    public string name {get; set;}
    public string paramtype {get; set;}
    public string source {get; set;}
}

IEnumerable<Parameter> parameters;

还有一个字符串数组,我想检查它.

And a array of strings i want to check it against.

string[] myStrings = new string[] { "one", "two"};

我想遍历参数列表并检查源属性是否等于任何 myStrings 数组.我可以用嵌套的 foreach 来做到这一点,但我想学习如何以更好的方式做到这一点,因为我一直在玩 linq 并且喜欢可枚举的扩展方法,比如 where 等,所以嵌套的 foreachs 感觉不对.有没有更优雅的首选 linq/lambda/delegete 方式来做到这一点.

I want to iterate over the parameter list and check if the source property is equal to any of the myStrings array. I can do this with nested foreach's but i would like to learn how to do it in a nicer way as i have been playing around with linq and like the extension methods on enumerable like where etc so nested foreachs just feel wrong. Is there a more elegant preferred linq/lambda/delegete way to do this.

谢谢

推荐答案

您可以使用嵌套的 Any() 进行此检查,该检查可在任何 Enumerable 上使用:

You could use a nested Any() for this check which is available on any Enumerable:

bool hasMatch = myStrings.Any(x => parameters.Any(y => y.source == x));

在更大的集合上更快地执行是将 parameters 投影到 source,然后使用 Intersect,它在内部使用 HashSet; 因此,对于第一种方法(相当于两个嵌套循环),您可以在 O(n) 中进行检查,而不是 O(n^2) :

Faster performing on larger collections would be to project parameters to source and then use Intersect which internally uses a HashSet<T> so instead of O(n^2) for the first approach (the equivalent of two nested loops) you can do the check in O(n) :

bool hasMatch = parameters.Select(x => x.source)
                          .Intersect(myStrings)
                          .Any(); 

另外作为旁注,您应该将类​​名和属性名大写以符合 C# 样式指南.

Also as a side comment you should capitalize your class names and property names to conform with the C# style guidelines.

这篇关于检查是否 list<t>包含任何其他列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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