Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare the difference between two list<string>

I'am trying to check the difference between two List<string> in c#.

Example:

List<string> FirstList = new List<string>();
List<string> SecondList = new List<string>();

The FirstList is filled with the following values:

FirstList.Add("COM1");
FirstList.Add("COM2");

The SecondList is filled with the following values:

SecondList.Add("COM1");
SecondList.Add("COM2");
SecondList.Add("COM3");

Now I want to check if some values in the SecondList are equal to values in the FirstList.

If there are equal values like: COM1 and COM2, that are in both lists, then filter them from the list, and add the remaining values to another list.

So if I would create a new ThirdList, it will be filled with "COM3" only, because the other values are duplicates.

How can I create such a check?

like image 725
Max Avatar asked Mar 25 '13 10:03

Max


People also ask

How do I compare two lists of strings in Java?

Java provides a method for comparing two Array List. The ArrayList. equals() is the method used for comparing two Array List. It compares the Array lists as, both Array lists should have the same size, and all corresponding pairs of elements in the two Array lists are equal.


2 Answers

Try to use Except LINQ extension method, which takes items only from the first list, that are not present in the second. Example is given below:

List<string> ThirdList =  SecondList.Except(FirstList).ToList();

You can print the result using the following code:

Console.WriteLine(string.Join(Environment.NewLine, ThirdList));

Or

Debug.WriteLine(string.Join(Environment.NewLine, ThirdList));

Note: Don't forget to include: using System.Diagnostics;

prints:

COM3
like image 104
Ilya Ivanov Avatar answered Sep 20 '22 21:09

Ilya Ivanov


You can use Enumerable.Intersect:

var inBoth = FirstList.Intersect(SecondList);

or to detect strings which are only in one of both lists, Enumerable.Except:

var inFirstOnly = FirstList.Except(SecondList);
var inSecondOnly = SecondList.Except(FirstList);

To get your ThirdList:

List<string> ThirdList = inSecondOnly.ToList();
like image 31
Tim Schmelter Avatar answered Sep 21 '22 21:09

Tim Schmelter