C#比较两个list集合类的差异

C#中List中自带的差集计算方法

List 继承了Enumerable ,Enumerable 中有一个Except方法
在这里插入图片描述

它有两个实现:

第一个实现是通过使用默认的相等比较器对值进行比较,生成两个序列的差集。
第二个实现是通过使用指定的 IEqualityComparer 对值进行比较,生成两个序列的差集。
简单数值对比
这是用默认的相等对比器
这种方式一般都是用来比较简单数组或者字符串内容

double[] numbers1 = { 2.0, 2.0, 2.1, 2.2, 2.3, 2.3, 2.4, 2.5 };
double[] numbers2 = { 2.2 };

IEnumerable<double> onlyInFirstSet = numbers1.Except(numbers2);

foreach (double number in onlyInFirstSet)
    Console.WriteLine(number);

问题:

如果list集合类的差异的话,直接使用List中的Except方法,会发现全部都不一样。这就是问题。

结论:

解决方案:可以把集合类事先转换为ToJson的字符串,就可以使用List中的Except方法。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# 中,你可以使用 LINQ 来比较两个 List差异。下面是几种常见的方法: 1. 查找差异元素: ```csharp List<int> list1 = new List<int> { 1, 2, 3, 4 }; List<int> list2 = new List<int> { 3, 4, 5, 6 }; List<int> added = list2.Except(list1).ToList(); // 获取 list2 中不在 list1 中的元素 List<int> removed = list1.Except(list2).ToList(); // 获取 list1 中不在 list2 中的元素 ``` 在上述代码中,`added` 列表将包含 `list2` 中不在 `list1` 中的元素(5 和 6),而 `removed` 列表将包含 `list1` 中不在 `list2` 中的元素(1 和 2)。 2. 查找差异项的索引: ```csharp List<int> list1 = new List<int> { 1, 2, 3, 4 }; List<int> list2 = new List<int> { 3, 4, 5, 6 }; var addedIndexes = list2.Select((value, index) => new { value, index }) .Where(item => !list1.Contains(item.value)) .Select(item => item.index) .ToList(); // 获取 list2 中不在 list1 中的元素的索引 var removedIndexes = list1.Select((value, index) => new { value, index }) .Where(item => !list2.Contains(item.value)) .Select(item => item.index) .ToList(); // 获取 list1 中不在 list2 中的元素的索引 ``` 在上述代码中,`addedIndexes` 列表将包含 `list2` 中不在 `list1` 中的元素的索引(2 和 3),而 `removedIndexes` 列表将包含 `list1` 中不在 `list2` 中的元素的索引(0 和 1)。 这些只是比较两个 List 差异的简单示例。根据你的具体需求,你可能需要使用更复杂的比较逻辑或使用其他方法来处理差异

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值