本文介绍了比较两个列表℃之间的差异;串>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我'尝试检查的区别两个列表<串>以 C#



例如:

 列表<串GT; FirstList =新的List<串GT;(); 
名单,LT;字符串> SecondList =新的List<串GT;();



FirstList 填充以下值

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



SecondList 填充以下值

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

现在我要检查,如果在 SecondList 等于在值 FirstList



如果有喜欢的相等值:COM1和COM2,这是两个列表,然后从列表中进行筛选,剩下的值添加到另一个列表。



所以,如果我想创建一个新的 ThirdList ,这将只充斥着COM3,因为其他值是重复的。



如何创建这样的检查

解决方案

尝试使用的 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

这篇关于比较两个列表℃之间的差异;串&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 11:00