简体   繁体   English

在使用linq查询的运算符中

[英]In operator using linq query

I have a list of items (InputList). 我有一个项目列表(InputList)。 Along with this I have a list of names (Names). 与此同时,我还有一个名称列表(名称)。 Now I need only those items from InputList whose names are present in the Names list. 现在,我只需要名称列表中存在名称的InputList项目。

One solution is that I do a loop on Names list and check if it is present in InputList or not. 一种解决方案是我对“名称”列表进行循环,并检查它是否存在于InputList中。

foreach (var name in names)
{
    var result = InputList.FirstOrDefault(i => i.Name == name);
    if (result != null)
        outputList.Add(result);
}

There is IN operator in SQL in which we provide list and query returns desired result. SQL中有IN运算符,其中提供了列表,查询返回了所需的结果。 Can I achieve the same using Linq? 我可以使用Linq达到相同的目的吗?

That you want is the following: 您想要的是以下内容:

var result = inputList.Where(x=>Names.Contains(x.Name));

the above query selects all the elements of inputList, whose name is contained in the Names list. 上面的查询选择inputList的所有元素,其名称包含在Names列表中。

The signature of Contains method is bool Contains(T item) , where T is the type of objects that are contained in your list. Contains方法的签名是bool Contains(T item) ,其中T是列表中包含的对象的类型。 If the item you pass to this method is contained in your list returns true. 如果您传递给此方法的项目包含在列表中,则返回true。 Otherwise, it returns false. 否则,它返回false。

For further documentation on the Contains method, please have a look here . 有关Contains方法的更多文档,请在此处查看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM