using System;
using System.Collections.Generic;
using System.Linq;
namespace List集合通用去重扩展方法_支持单键_多键去重_全局可复用
{
// 实体
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
public static class ListExtension
{
/// <summary>
/// 根据单个字段去重
/// </summary>
/// <typeparam name="T">集合元素类型</typeparam>
/// <typeparam name="TKey">比对键类型</typeparam>
/// <param name="source">源集合</param>
/// <param name="keySelector">去重字段</param>
/// <returns>去重后集合</returns>
public static List<T> DistinctByKey<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector)
{
HashSet<TKey> hash = new HashSet<TKey>();
List<T> result = new List<T>();
foreach (var item in source)
{
if (hash.Add(keySelector(item)))
{
result.Add(item);
}
}
return result;
}
/// <summary>
/// 多字段组合去重
/// </summary>
public static List<T> DistinctByMultiKey<T>(this IEnumerable<T> source, params Func<T, object>[] keySelectors)
{
HashSet<string> hash = new HashSet<string>();
List<T> result = new List<T>();
foreach (var item in source)
{
string key = string.Join("|", keySelectors.Select(f => f(item)));
if (hash.Add(key))
{
result.Add(item);
}
}
return result;
}
}
class Program
{
static void Main()
{
// 造测试数据
List<User> userList = new List<User>
{
new User{Id=1,Name="张三"},
new User{Id=2,Name="李四"},
new User{Id=1,Name="张三"}
};
// 1.按单个字段去重
List<User> res1 = userList.DistinctByKey(u => u.Id);
// 2.按多个字段联合去重
List<User> res2 = userList.DistinctByMultiKey(u => u.Id, u => u.Name);
// 3.值类型集合同样适用
List<int> numList = new List<int> { 1, 2, 2, 3 };
List<int> numRes = numList.DistinctByKey(x => x);
//使用说明:
//项目引用该扩展类,任意List / IEnumerable直接点方法调用
//底层基于HashSet,查询效率高,保留原始顺序
//兼容值类型、自定义实体,全项目通用
//关键注意点:
//缺少命名空间会找不到扩展方法,务必添加using Common.Extensions;
//支持List、IEnumerable等可枚举集合
//保留原始数据顺序,去重效率高
//多字段拼接分隔符避免关键字冲突即可
}
}
}