技术文摘
C#数据去重的五种方法,您知晓多少?
2024-12-30 17:25:04 小编
C#数据去重的五种方法,您知晓多少?
在 C#编程中,数据去重是一项常见且重要的任务。下面将为您介绍五种常用的数据去重方法。
方法一:使用 HashSet 类 HashSet 是一个不允许重复元素的集合。通过将数据添加到 HashSet 中,它会自动去除重复项。这种方法简单高效,适用于较小规模的数据。
HashSet<int> uniqueNumbers = new HashSet<int>();
int[] numbers = { 1, 2, 2, 3, 3, 3 };
foreach (int num in numbers)
{
uniqueNumbers.Add(num);
}
方法二:使用 LINQ 的 Distinct 方法 LINQ(Language Integrated Query)提供了 Distinct 方法来进行数据去重。
int[] numbers = { 1, 2, 2, 3, 3, 3 };
var uniqueNumbers = numbers.Distinct();
方法三:自定义比较器 如果数据类型没有默认的相等比较方式,可以自定义比较器来实现去重。
class CustomComparer : IEqualityComparer<int>
{
public bool Equals(int x, int y)
{
return x == y;
}
public int GetHashCode(int obj)
{
return obj.GetHashCode();
}
}
int[] numbers = { 1, 2, 2, 3, 3, 3 };
var uniqueNumbers = numbers.Distinct(new CustomComparer());
方法四:排序后去重 先对数据进行排序,然后遍历去除相邻的重复项。
int[] numbers = { 1, 2, 2, 3, 3, 3 };
Array.Sort(numbers);
int index = 0;
for (int i = 1; i < numbers.Length; i++)
{
if (numbers[i]!= numbers[index])
{
index++;
numbers[index] = numbers[i];
}
}
方法五:使用字典 将数据作为键添加到字典中,利用字典键的唯一性实现去重。
Dictionary<int, int> uniqueNumbers = new Dictionary<int, int>();
int[] numbers = { 1, 2, 2, 3, 3, 3 };
foreach (int num in numbers)
{
uniqueNumbers[num] = 1;
}
以上就是 C#中常见的五种数据去重方法,您可以根据具体的场景和需求选择合适的方法。每种方法都有其特点和适用范围,灵活运用能够提高编程效率和代码质量。
- 微软 Win11 22H2 RTM 正式版被定为 Build 22621.382 消息传出
- CentOS6 32/64 位安装 Adobe Flash Player 组件的步骤
- Win11 预览版 Build 22000.918(KB5016691)发布 解决 USB 打印等问题
- Win11 键盘无法使用的解决办法及修复登录时键盘不工作的技巧
- CentOS 在 VPS 上添加硬盘无需重启服务器的详细方法
- 阿里云 CentOS 系统通过 yum 安装 vsftpd
- CentOS7 主机名修改方式
- Centos6.5 SSH 免密码登录配置指南
- YUM 更换源及找不到安装包的解决办法
- 如何修复 win11 错误代码 0xA00F4288 及相机应用程序错误
- CentOS 中 Tree 插件的使用指南及注意要点
- 如何让 CentOS 虚拟机进入救援模式
- 如何解决 Win11/10 热跳闸错误及电脑 CPU 高温重启问题
- Centos 安装 Docker 前升级内核至 3.10 的方法
- 如何修复 Win11 系统中 SystemSettings.exe 停止工作的问题