C# 两个list进行数据比对
时间: 2024-02-05 14:46:55 浏览: 120
可以使用 LINQ 中的 `Except` 方法来实现两个 `List` 的数据比对。
`Except` 方法可以返回第一个 `List` 中不包含在第二个 `List` 中的元素。
示例代码如下:
```csharp
List<int> list1 = new List<int> { 1, 2, 3, 4, 5 };
List<int> list2 = new List<int> { 3, 4, 5, 6, 7 };
var result = list1.Except(list2);
foreach (var item in result)
{
Console.WriteLine(item); // 输出:1 2
}
```
以上代码中,`result` 变量中存储了 `list1` 中不包含在 `list2` 中的元素。你可以将 `int` 替换为你需要比对的类型。
相关问题
C# 两个List集合进行对比返回不同
可以使用 LINQ 中的 Except 方法来实现两个 List 集合的比较,返回不同的元素。具体实现方法如下:
```csharp
List<int> list1 = new List<int> { 1, 2, 3, 4 };
List<int> list2 = new List<int> { 3, 4, 5, 6 };
var differentItems = list1.Except(list2).Concat(list2.Except(list1));
```
以上代码中,我们分别使用 Except 方法得到 list1 中有而 list2 中没有的元素,以及 list2 中有而 list1 中没有的元素。最后将这两个结果合并起来,就可以得到两个集合中不同的元素。在上面的例子中,differentItems 的结果为 { 1, 2, 5, 6 }。
c# 两个List对比返回不同的list
可以使用 LINQ 的 Except 方法来实现。该方法用于获取一个集合中存在于另一个集合中的元素之外的所有元素。
下面是一个示例代码:
```csharp
List<int> list1 = new List<int> { 1, 2, 3, 4, 5 };
List<int> list2 = new List<int> { 3, 4, 5, 6, 7 };
List<int> differentList = list1.Except(list2).ToList();
foreach (int number in differentList)
{
Console.WriteLine(number);
}
```
在上面的代码中,我们有两个整数列表 `list1` 和 `list2`。我们使用 `Except` 方法来获取 `list1` 中存在但 `list2` 中不存在的元素,并将它们存储在 `differentList` 中。最后,我们遍历 `differentList` 并将结果打印到控制台上。
输出结果应该是:
```
1
2
```
因为在 `list1` 中只有 1 和 2 两个元素而它们都不存在于 `list2` 中。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)