Search code examples
c#linq

How to find items in one list that are present in another list?


List1 and List2 are the 2 lists which I have, expected output should look like list 3, How can I use LINQ in c# to achieve this.

Input List1 = {"test1", "test2","test3"};
Input List2 = {{"name": "test1", "value":1},{"name": "test2", "value":2},{"name": "test5", "value":5}};

Output List3 = {{"name": "test1", "value":1},{"name": "test2", "value":2}};

Solution

  • You could use a join:

    var query = from name in list1
                join item in list2
                on name equals item.name
                select item;
    
    var list3 = query.ToList();
    

    This approach would be efficicient if the lists are large.