LINQ - 比较List对象和字符串列表

时间:2017-02-09 07:41:10

标签: c# .net linq list

我有一个对象列表(List1)和一个字符串列表(List2 - 对象名称列表)

如果List2

中不存在object.Name,我需要从List1获取所有对象

如何写这个LINQ C#。?

2 个答案:

答案 0 :(得分:9)

public class Class1
{
    public string Name {get;set;}
}

var List1 = new List<Class1>();
var List2 = new List<string>();
var result = List1.Where(x=>!List2.Contains(x.Name)).ToList();

或者:

var result = List1.Where(x=>!List2.Any(n=>n==x.Name)).ToList();

答案 1 :(得分:0)

class Program
{
    static void Main(string[] args)
    {

        List<List1Class> listClass = new List<List1Class>();

        listClass.Add(new List1Class { ObjectName = "obj1" });
        listClass.Add(new List1Class { ObjectName = "obj2" });
        listClass.Add(new List1Class { ObjectName = "obj3" });
        listClass.Add(new List1Class { ObjectName = "obj4" });

        List<string> listString = new List<string>();
        listString.Add("obj2");
        listString.Add("obj4");
        listString.Add("obj5");

        var filterlist = listClass.Where(l => !listString.Contains(l.ObjectName)).ToList();

    }
}

类List1Class     {         public string ObjectName {get;组; }

    //Add other property
}