比较两个列表<string>的区别 [英] Compare the difference between two list<string>

查看:20
本文介绍了比较两个列表<string>的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查 c# 中两个 List<string> 之间的区别.

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

例子:

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

FirstList 填充了以下值:

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

SecondList 填充以下值:

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

现在我想检查 SecondList 中的某些值是否等于 FirstList 中的值.

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

如果两个列表中存在相同的值,例如:COM1 和 COM2,则从列表中过滤它们,并将剩余的值添加到另一个列表中.

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.

所以如果我要创建一个新的ThirdList,它将只填充COM3",因为其他值是重复的.

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

如何创建这样的支票?

推荐答案

尝试使用 Except LINQ 扩展方法,它只从第一个列表中获取第二个列表中不存在的项目.示例如下:

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));

或者

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

注意:不要忘记包括:using System.Diagnostics;

打印:

COM3

这篇关于比较两个列表&lt;string&gt;的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆