如果对象列表具有来自另一个列表的匹配元素

ali*_*ce7 0 c# linq lambda list

我有一个字符串列表

List<string> listOfStrings = {"1","2","3","4"};
Run Code Online (Sandbox Code Playgroud)

我有一个看起来像这样的对象列表

class Object A{
    string id;
    string Name;
}
Run Code Online (Sandbox Code Playgroud)

如何找到所有具有匹配字符串列表的对象。

我试过:

listOfA.Where(x => listoFstrings.Contains(x.id)).Select();
Run Code Online (Sandbox Code Playgroud)

但它不起作用,它正在拉动所有其他没有匹配字符串的对象。

Cᴏʀ*_*ᴏʀʏ 5

这是您的代码的可编译的工作版本:

// Specify list of strings to match against Id
var listOfStrings = new List<string> { "1", "2", "3", "4" };

// Your "A" class
public class A
{
    public string Id { get; set; }
    public string Name { get; set; }
}

// A new list of A objects with some Ids that will match
var listOfA = new List<A> 
{
    new A { Id = "2", Name = "A-2" },
    new A { Id = "4", Name = "A-4" },
};
Run Code Online (Sandbox Code Playgroud)

现在你应该可以使用你的原始代码,除了.Select()我使用的.ToList()

// Search for A objects in the list where the Id is part of your string list
var matches = listOfA.Where(x => listOfstrings.Contains(x.Id)).ToList();
Run Code Online (Sandbox Code Playgroud)