c#对象集合去重_C# List 根据对象属性去重的四种方法对比

private void TestDistinct()

{

Task.Run(() =>

{

//生成测试数据

DateTime dt = DateTime.Now;

Random rnd = new Random();

List list = new List();

int total = 1000000;

for (int i = 0; i < total; i++)

{

MyData info = new MyData();

info.id = rnd.Next(1, total * 10).ToString();

info.name = rnd.Next(1, total * 10).ToString();

list.Add(info);

}

double d = DateTime.Now.Subtract(dt).TotalMilliseconds;

//方法一

DateTime dt1 = DateTime.Now;

Dictionary result1 = new Dictionary();

foreach (MyData item in list)

{

MyData temp;

if (!result1.TryGetValue(item.name, out temp))

{

result1.Add(item.name, item);

}

}

List r1 = result1.Values.ToList();

double d1 = DateTime.Now.Subtract(dt1).TotalMilliseconds;

//方法二

DateTime dt2 = DateTime.Now;

List result2 = list.ToLookup(item => item.name).ToDictionary(item => item.Key, item => item.First()).Values.ToList();

double d2 = DateTime.Now.Subtract(dt2).TotalMilliseconds;

//方法三

DateTime dt3 = DateTime.Now;

List result3 = list.Distinct(new MyCompare()).ToList();

double d3 = DateTime.Now.Subtract(dt3).TotalMilliseconds;

//方法四

DateTime dt4 = DateTime.Now;

List result4 = list.GroupBy(item => item.name).Select(item => item.First()).ToList();

double d4 = DateTime.Now.Subtract(dt4).TotalMilliseconds;

this.BeginInvoke(new Action(() =>

{

textBox1.Text = "";

textBox1.Text += "生成 " + list.Count.ToString("# ####") + " 条测试数据耗时:" + d + "毫秒\r\n\r\n";

textBox1.Text += "使用方法一去重耗时:" + d1 + "毫秒\r\n\r\n";

textBox1.Text += "使用ToLookup和ToDictionary去重耗时:" + d2 + "毫秒\r\n\r\n";

textBox1.Text += "使用Distinct去重耗时:" + d3 + "毫秒\r\n\r\n";

textBox1.Text += "使用GroupBy和Select去重耗时:" + d4 + "毫秒\r\n\r\n";

textBox1.Text += "去重后数量:" + r1.Count + "," + result2.Count + "," + result3.Count + "," + result4.Count + "" + "\r\n\r\n";

}));

});

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值