Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...