5

I have a list of objects (List1) and list of string (List2 - list of Names of the objects)

I need to get all objects from List1 if the object.Name does not exists in List2

How can write this LINQ C#.?

1

2 Answers 2

13
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();

Or:

var result = List1.Where(x=>!List2.Any(n=>n==x.Name)).ToList();
Sign up to request clarification or add additional context in comments.

Comments

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();

    }
}

class List1Class { public string ObjectName { get; set; }

    //Add other property
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.