使用linq检查一个数组中的值是否在另一个数组中 [英] Check if a value from one array exists in another array using linq
问题描述
我有一个列表,其中myclass定义了一些属性
I've got an list where myclass is defined with a few properties
List<MyClass> myClassList = new List<MyClass>();
myClassList.Add(new MyClass() { Id = 1, Name = "My first test", Key = "First" });
myClassList.Add(new MyClass() { Id = 2, Name = "My second test", Key = "Second" });
然后我有一个路径,即c:\ my文件夹\公司名称\ My First Test,我使用正则表达式(即myArrayPath)将其分成一个字符串数组
I then have a path i.e. c:\my folders\company name\My First Test, which I break into a string array using regex i.e. myArrayPath
我想查找基于给定属性的myClassList的任何元素(即Name)是否可以在myArrayPath的任何元素中找到,理想情况下,我想返回Key,但是如果我返回与元素之一匹配的对象从myArrayPath中获得的效果也一样.
I want to find if any elements of myClassList based on a given property i.e. Name can be found in any of the elements from myArrayPath and ideally I'd like to return the Key but if I return the object matching one of the element from myArrayPath, this will be just as good.
是否有一种使用linq和/或lambda表达式来实现此目标的方法.
Is there a way to achieve this using linq and/or lambda expressions.
谢谢.
推荐答案
使用LINQ可以很容易地做到这一点:
This can be quite easily done with LINQ:
var keyResult = myClassList.Where(x=>myArrayPath.Contains(x.Name))
.Select(x=>x.Key);
如果您需要数组列表的形式,只需在其末尾添加.ToList()
或.ToArray()
.
if you need it in the form of a list of an array, just add .ToList()
or .ToArray()
at the end of it.
这篇关于使用linq检查一个数组中的值是否在另一个数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!