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

时间:2014-06-05 17:22:50

标签: c# linq list lambda

我有一个字符串列表

List<string> listOfStrings = {"1","2","3","4"};

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

class Object A{
    string id;
    string Name;
}

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

我试过了:

listOfA.Where(x => listoFstrings.Contains(x.id)).Select();

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

1 个答案:

答案 0 :(得分:4)

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

// 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" },
};

现在您应该能够使用原始代码,而不是.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();
相关问题