比较两个集合的C#的更有效的方法 [英] C# more efficient way of comparing two collections

查看:237
本文介绍了比较两个集合的C#的更有效的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个集合

List<Car> currentCars = GetCurrentCars();
List<Car> newCars = GetNewCars();

我不希望使用foreach循环或东西,因为我觉得应该有这样做的更好的方法。

I don't want to use foreach loop or something because i think there should be much better way of doing this.

我要寻找到比较这集合和得到的结果更有效的方式:

I am looking for more efficient way to compare this collections and to get results:

  1. 在汽车这是在newCars,而不是在currentCars名单
  2. 在汽车,这是不newCars以及在currentCars列表

类型的车有整型属性标识。

Type Car has int property Id.

有一个答案,这是已经被删除话 我的意思是说有效的:少code,少力学,更可读的情况下

There was an answer, which is already deleted saying What i mean by saying efficient: less code, less mechanics, and more readable cases

所以,这样的想法是什么情况下,我有吗?

So thinking this way what is the cases i have?

什么是少code,少力学,更具可读性的情况下?

What would be less code, less mechanics, and more readable cases?

推荐答案

您可以使用除了

var currentCarsNotInNewCars = currentCars.Except(newCars);
var newCarsNotInCurrentCars = newCars.Except(currentCars);

但是,这已超过了的foreach 解决方案没有性能优势。它只是看起来比较清爽。
另外,要注意的事实,你需要实现 IEquatable&LT; T&GT; 类,所以比较是在ID和不在参考

But this has no performance benefit over the foreach solution. It just looks cleaner.
Also, be aware of the fact, that you need to implement IEquatable<T> for your Car class, so the comparison is done on the ID and not on the reference.

Performancewise,更好的办法是不使用名单,其中,T&GT; 词典&LT; TKEY的,TValue&GT; 的ID作为关键的:

Performancewise, a better approach would be to not use a List<T> but a Dictionary<TKey, TValue> with the ID as the key:

var currentCarsDictionary = currentCars.ToDictionary(x => x.ID);
var newCarsDictionary = newCars.ToDictionary(x => x.ID);

var currentCarsNotInNewCars = 
    currentCarsDictionary.Where(x => !newCarsDictionary.ContainsKey(x.Key))
                         .Select(x => x.Value);

var newCarsNotInCurrentCars = 
    newCarsDictionary.Where(x => !currentCarsDictionary.ContainsKey(x.Key))
                     .Select(x => x.Value);

这篇关于比较两个集合的C#的更有效的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆