28

I have two lists of strings. How do I get the list of distinct values between them or remove the second list elements from the first list?

List<string> list1 = { "see","you","live"}

List<string> list2 = { "see"}

The result should be {"you","live"}.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
kartal
  • 17,436
  • 34
  • 100
  • 145

4 Answers4

71

It looks to me like you need Enumerable.Except():

var differences = list1.Except(list2);

And then you can loop through the differences:

foreach(var difference in differences)
{
    // work with each individual string here.
}
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
14

If you want to get items from the first list except items in the second list, use

list1.Except(list2)

If you want to get items that are in the first list or in the second list, but not both, you can use

list1.Except(list2).Concat(list2.Except(list1))
svick
  • 236,525
  • 50
  • 385
  • 514
  • 2
    If anybody comes here for for "items that are in the first list or in the second list, but not both", you can simply use `list1.Union(list2)` – sirius Oct 01 '18 at 11:03
  • I misunderstood your comment expected the union result to not contain any of the items that were duplicates. I realized Union is just the deduped merger of 2 lists. – Kcats Wolfrevo Aug 28 '20 at 09:58
6

This is the good way I find unique....

Unique from two list

        var A = new List<int>() { 1,2,3,4 };
        var B = new List<int>() { 1, 5, 6, 7 };

       var a= A.Except(B).ToList();
        // outputs List<int>(2) { 2,3,4 }
       var b= B.Except(A).ToList();
        // outputs List<int>(2) { 5,6,7 }
       var abint=  B.Intersect(A).ToList();
        // outputs List<int>(2) { 1 }
Sanjay Dwivedi
  • 699
  • 7
  • 10
0

Here is my answer. Find distinct values in two int lists and assign those values to the third int list.

List<int> list1 = new List <int>() { 1, 2, 3, 4, 5, 6 }; 
List<int> list2 = new List<int>() { 1, 2, 3, 7, 8, 9 };
List<int> list3 = new List<int>();
var DifferentList1 = list1.Except(list2).Concat(list2.Except(list1));

foreach (var item in DifferentList1)
{
    list3.Add(item);

}

foreach (var item in list3)
{
    Console.WriteLine("Different Item found in lists are{0}",item);
}

Console.ReadLine();
Gudarzi
  • 486
  • 3
  • 7
  • 22
  • Please provide additional details in your answer. As it's currently written, it's hard to understand your solution. – Community Sep 02 '21 at 13:47