从 C# 中的列表中删除重复项
本教程将介绍从 C# 中的列表中删除重复元素的方法。
使用 C# 中的 HashSet 类从列表中删除重复项
HashSet 类用于在 C# 中创建一个集合。集合是众所周知的不同对象的无序集合,这意味着集合的元素是无序的,不会重复。我们可以通过将列表存储到 HashSet 中,然后使用 LINQ 的 ToList() 函数将该 HashSet 转换回列表中来删除列表中的重复元素。以下代码示例向我们展示了如何使用 C# 中的 HashSet 类从列表中删除重复的元素。
using System;
using System.Collections.Generic;
using System.Linq;
namespace remove_duplicates_from_list {
class Program {
static void displayList(List<int> list) {
foreach (var item in list) {
Console.WriteLine(item);
}
}
static void Main(string[] args) {
List<int> listWithDuplicates = new List<int> { 1, 2, 1, 2, 3, 4, 5 };
HashSet<int> hashWithoutDuplicates = new HashSet<int>(listWithDuplicates);
List<int> listWithoutDuplicates = hashWithoutDuplicates.ToList();
displayList(listWithoutDuplicates);
}
}
}
输出:
1
2
3
4
5
我们在上面的代码中声明并初始化了具有重复值 listWithDuplicates 的整数列表。然后,通过在 HashSet 类的构造函数中传递列表,将列表转换为 hasWithoutDuplicates 集。然后,我们使用 LINQ ToList() 方法将集合转换回整数列表 listWithoutDuplicates。最后,我们在 listWithoutDuplicates 列表中显示了元素。
使用 C# 中的 LINQ 方法从列表中删除重复项
LINQ 将查询功能集成到 C# 的数据结构中。LINQ 的 Distinct() 函数用于从 C# 的数据结构中选择唯一值。LINQ 的 ToList() 函数将元素集合转换为 C# 中的列表。我们可以使用 Distinct() 函数从列表中选择唯一的,非重复的值,然后使用 LINQ 的 ToList() 函数将选定的值转换回列表。以下代码示例向我们展示了如何使用 C# 中的 LINQ 方法从列表中删除重复值。
using System;
using System.Collections.Generic;
using System.Linq;
namespace remove_duplicates_from_list {
class Program {
static void displayList(List<int> list) {
foreach (var item in list) {
Console.WriteLine(item);
}
}
static void Main(string[] args) {
List<int> listWithDuplicates = new List<int> { 1, 2, 1, 2, 3, 4, 5 };
List<int> listWithoutDuplicates = listWithDuplicates.Distinct().ToList();
displayList(listWithoutDuplicates);
}
}
}
输出:
1
2
3
4
5
我们在上面的代码中声明并初始化了具有重复值 listWithDuplicates 的整数列表。然后,我们使用 LINQ 的 Distinct() 函数从此列表中选择唯一值。然后,我们使用 LINQ ToList() 函数将选定的值转换为整数列表 listWithoutDuplicates。
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn