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"};
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.
我想迭代参数列表并检查source属性是否等于任何myStrings数组。我可以用嵌套的foreach来做到这一点,但我想学习如何以更好的方式做到这一点,因为我一直在玩linq,就像可枚举的扩展方法一样,所以嵌套的foreachs只是感觉不对。有没有更优雅的首选linq / lambda / delegete方法来做到这一点。
Thanks
谢谢
1 个解决方案
#1
115
You could use a nested Any()
for this check which is available on any Enumerable
:
您可以使用嵌套的Any()进行此检查,该检查可用于任何Enumerable:
bool hasMatch = myStrings.Any(x => parameters.Any(y => y.source == x));
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) :
在较大的集合上执行速度更快的是将参数投影到源,然后使用Intersect,它在内部使用HashSet
bool hasMatch = parameters.Select(x => x.source)
.Intersect(myStrings)
.Any();
Also as a side comment you should capitalize your class names and property names to conform with the C# style guidelines.
另外,作为附注,您应该将您的类名和属性名称大写,以符合C#样式指南。
#1
115
You could use a nested Any()
for this check which is available on any Enumerable
:
您可以使用嵌套的Any()进行此检查,该检查可用于任何Enumerable:
bool hasMatch = myStrings.Any(x => parameters.Any(y => y.source == x));
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) :
在较大的集合上执行速度更快的是将参数投影到源,然后使用Intersect,它在内部使用HashSet
bool hasMatch = parameters.Select(x => x.source)
.Intersect(myStrings)
.Any();
Also as a side comment you should capitalize your class names and property names to conform with the C# style guidelines.
另外,作为附注,您应该将您的类名和属性名称大写,以符合C#样式指南。