且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

比较两个列表℃之间的差异;串>

更新时间:2023-11-08 22:58:28

尝试使用的 LINQ扩展方法,该方法只能从第一列表中的项目,即不存在于第二个。例子如下:

 列表<串GT; ThirdList = SecondList.Except(FirstList).ToList(); 

您可以使用下面的代码打印结果:

  Console.WriteLine(的string.join(Environment.NewLine,ThirdList)); 

 的Debug.WriteLine(的string.join(Environment.NewLine,ThirdList)); 

请注意:不要忘记包括:使用System.Diagnostics程序;



打印:

  COM3 


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?

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