随笔 - 56  文章 - 0  评论 - 0  阅读 - 12958

List去重方法

方法一:遍历list

循环遍历List,借助Dictionary存储去重的对象

Dictionary<string, Item> result = new Dictionary<string, Item>();
foreach (Item item in list)//list为待去重列表
{
Item temp;
if (!result.TryGetValue(item.name, out temp))
{
result.Add(item.name, item);
}
}
List<Item> result_list = result.Values.ToList();
///Item
public class Item
{
public string name { get; set; }
public string value { get; set; }
}

方法二:ToLookup

利用ToLookup查找,并转为Dictionary

List<Item> result = list.ToLookup(item => item.name).ToDictionary(item => item.Key, item => item.First()).Values.ToList();
///Item
public class Item
{
public string name { get; set; }
public string value { get; set; }
}

方法三:自定义Compare

自定义Compare方法实现

List<Item> result = list.Distinct(new Compare()).ToList();
//compare方法
public class Compare : IEqualityComparer<Item>
{
public bool Equals(Item a, Item b)
{
return a.name == b.name;
}
public int GetHashCode(Item obj)
{
return obj.name.GetHashCode();
}
}
///Item
public class Item
{
public string name { get; set; }
public string value { get; set; }
}

Compare公用方法

public class Compare<T, C> : IEqualityComparer<T>
{
private Func<T, C> _getField;
public Compare(Func<T, C> getfield)
{
this._getField = getfield;
}
public bool Equals(T x, T y)
{
return EqualityComparer<C>.Default.Equals(_getField(x), _getField(y));
}
public int GetHashCode(T obj)
{
return EqualityComparer<C>.Default.GetHashCode(this._getField(obj));
}
}
public static class CommonHelper
{
/// <summary>
/// 自定义Distinct扩展方法
/// </summary>
/// <typeparam name="T">要去重的对象类</typeparam>
/// <typeparam name="C">自定义去重的字段类型</typeparam>
/// <param name="source">要去重的对象</param>
/// <param name="getfield">获取自定义去重字段的委托</param>
/// <returns></returns>
public static IEnumerable<T> MyDistinct<T, C>(this IEnumerable<T> source, Func<T, C> getfield)
{
return source.Distinct(new Compare<T, C>(getfield));
}
}
//调用
list.MyDistinct(s=>s.Id).ToList().ForEach(s => Console.WriteLine(s.ToString()));

方法四:groupby

利用GroupBy分组实现

List<Item> result = list.GroupBy(item => item.name).Select(item => item.First()).ToList();
///Item
public class Item
{
public string name { get; set; }
public string value { get; set; }
}

总结:方法一和方法三去重效率差不多,方法二和方法四去重效率差不多,但是方法一和方法三的效率是方法二和方法四的四倍左右,所以推荐使用方法三。

posted on   Jeffrey~~  阅读(31)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示