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#.?

Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49
Sahi
  • 1,454
  • 1
  • 13
  • 32
  • Possible duplicate of [Quickest way to compare two List<>](https://stackoverflow.com/questions/12795882/quickest-way-to-compare-two-list). I realize this is `string` vs. `object`, but [Skeet's answer refers to that issue specifically in the comments as well](https://stackoverflow.com/questions/12795882/quickest-way-to-compare-two-list#comment60600663_12795900). – ruffin Oct 15 '18 at 13:00

2 Answers2

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();
Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49
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
}
Amol B Lande
  • 242
  • 1
  • 2
  • 13