.Net Collection Distinct 去重

2023-05-16,,

由于业务场景的需要,海量的数据需要进行处理、组装,难免会出现冗余的重复数据。如何处理重复的数据就是一个问题。

简单的集合中,去重就可以用linq distinct来完成。对于复杂的集合直接使用distinct就会显得没那么有效了。

造数据

构造1M的orderentity,非重复的数据为1M/2.

 IList<OrderEntity> sourceList = new List<OrderEntity>();
for (int i = ; i < ; i++)
{
OrderEntity o = new OrderEntity
{
OrderNo = i % ,
Amount = ,
Detail = "test"
};
sourceList.Add(o);
}

方式一:直接distinct

 var list = sourceList.Distinct().ToList();
Console.WriteLine(list.Count + " 耗时:" + watch.ElapsedMilliseconds);

结果还是1M,对于复杂的集合 distinct直接使用是没效果的。

方法二:对数据分组

 var list2 = sourceList.GroupBy(t => new
{
t.OrderNo,
t.Amount,
t.Detail }).Select(g => g.First()).ToList(); Console.WriteLine(list2.Count + " 耗时:" + watch.ElapsedMilliseconds);

结果是500K, 对集合group处理还是有作用的,可惜的是耗时较高。

方法三:推荐 使用Distinct 重载

 public class OrderEntityComparer : IEqualityComparer<OrderEntity>
{
public bool Equals(OrderEntity x, OrderEntity y)
{
if (Object.ReferenceEquals(x, y)) return true;
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
return x.OrderNo == y.OrderNo && x.Amount == x.Amount && x.Detail == y.Detail;
} public int GetHashCode(OrderEntity obj)
{
//Check whether the object is null
if (Object.ReferenceEquals(obj, null)) return ;
//Get hash code for the Name field if it is not null.
int hashOrderNo = obj.OrderNo.GetHashCode(); //Get hash code for the Code field.
int hashAmount = obj.Amount.GetHashCode(); int hashDetail = obj.Detail == null ? : obj.Detail.GetHashCode();
//Calculate the hash code for the product.
return hashOrderNo ^ hashAmount ^ hashDetail;
}
}
  var list3 = sourceList.Distinct(new OrderEntityComparer()).ToList();

 Console.WriteLine(list3.Count + " 耗时:" + watch.ElapsedMilliseconds);

结果:达到去重目的,耗时也可以接受。

.Net Collection Distinct 去重的相关教程结束。

《.Net Collection Distinct 去重.doc》

下载本文的Word格式文档,以方便收藏与打印。