Compare the difference between two listlt;stringgt;(比较两个列表lt;stringgt;的区别)
问题描述
我正在尝试检查 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
这篇关于比较两个列表<string>的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:比较两个列表<string>的区别
基础教程推荐
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 将数据集转换为列表 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 如果条件可以为空 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
