c#两个listA,listB,判断是否有重复,并输入不重复的listA的数据
时间: 2025-09-02 17:23:11 AIGC 浏览: 14
在 C# 中,可以使用多种方法来判断两个列表 `listA` 和 `listB` 是否有重复元素,并输出 `listA` 中不重复的元素。
### 使用 `Any` 方法判断是否有重复元素
```csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> listA = new List<int> { 1, 2, 3, 4, 5 };
List<int> listB = new List<int> { 4, 5, 6, 7, 8 };
bool hasDuplicates = listA.Any(item => listB.Contains(item));
if (hasDuplicates)
{
Console.WriteLine("两个列表有重复元素。");
}
else
{
Console.WriteLine("两个列表没有重复元素。");
}
var uniqueElements = listA.Where(item =>!listB.Contains(item)).ToList();
Console.WriteLine("listA 中不重复的元素:");
foreach (var element in uniqueElements)
{
Console.WriteLine(element);
}
}
}
```
上述代码通过 `Any` 方法结合 `Contains` 方法判断 `listA` 中是否有元素存在于 `listB` 中,以此判断是否有重复元素。然后使用 `Where` 方法筛选出 `listA` 中不在 `listB` 中的元素,即不重复元素。
### 使用 `HashSet` 方法判断是否有重复元素
```csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> listA = new List<int> { 1, 2, 3, 4, 5 };
List<int> listB = new List<int> { 4, 5, 6, 7, 8 };
HashSet<int> setB = new HashSet<int>(listB);
bool hasDuplicates = false;
List<int> uniqueElements = new List<int>();
foreach (var item in listA)
{
if (setB.Contains(item))
{
hasDuplicates = true;
}
else
{
uniqueElements.Add(item);
}
}
if (hasDuplicates)
{
Console.WriteLine("两个列表有重复元素。");
}
else
{
Console.WriteLine("两个列表没有重复元素。");
}
Console.WriteLine("listA 中不重复的元素:");
foreach (var element in uniqueElements)
{
Console.WriteLine(element);
}
}
}
```
此代码将 `listB` 转换为 `HashSet`,因为 `HashSet` 的 `Contains` 方法查找元素的时间复杂度为 O(1),可以提高查找效率。然后遍历 `listA`,判断是否有重复元素,并筛选出不重复元素。
阅读全文
相关推荐




















