检查列表< T>包含任何其他名单 [英] Check if list<t> contains any of another list

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

问题描述

我有这样的参数列表:

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和像枚举扩展方法,如在这里等这样的嵌套foreachs只是觉得不对玩耍。是否有一个更优雅的preferred LINQ /λ/ 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.

感谢

推荐答案

您可以使用嵌套的任何()此检查是可以在任何可枚举

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

更快的表演大集合将项目参数,然后用相交在内部使用的HashSet&LT; T&GT; 等等,而不是为O(n ^ 2)对于第一种方法(两个嵌套循环的当量)你可以在O检查(N):

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.

这篇关于检查列表&LT; T&GT;包含任何其他名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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