Comapring two List<String> to extract the common items and put it in List

11,386

Solution 1

Use the LINQ Intersect method.

 var commonItems = a.Intersect(b);

variable commonItems will be a collection of common items from list a and list b , which is ["c","d"]

Solution 2

You can also call List.FindAll:

List<string> listA = {a, b, c, d}
List<string> listB = {c, d, e, f}

List<string> listC = listA.FindAll(elem => listB.Contains(elem));

Solution 3

Because they're common to both lists, we can just grab the items from one list that are also in the other. Like this:

List<string> c = a.Intersect(b)
                  .ToList();

This can be read as: "Select items from list a such that at least one item from list b has the same value."

Note that this only works for value types and reference types with a usable equality method.

Solution 4

If you want to do this with a linq where query:

var c = a.Where(x => b.Contains(x))

Solution 5

The Linq way:

   List<string> c = (from i in a
                     join j in b
                     on i equals j
                     select i).ToList();
Share:
11,386
stranger
Author by

stranger

Updated on June 05, 2022

Comments

  • stranger
    stranger almost 2 years

    Im having two List items, how can I write a linq query to compare both and extract the common items.(Like List c, as shown below)

    List<string> a = {a, b, c, d}
    List<string> b = {c, d, e, f}
    
    List<string> c = {c, d}