内容简介:翻译自:https://stackoverflow.com/questions/6680487/c-sharp-more-efficient-way-of-comparing-two-collections
我有两个系列
List<Car> currentCars = GetCurrentCars(); List<Car> newCars = GetNewCars();
我不想使用foreach循环或其他东西,因为我认为应该有更好的方法来做到这一点.
我正在寻找更有效的方法来比较这个集合并获得结果:
>在newCars中而不在currentCars中的汽车列表
>不在newCars和currentCars中的汽车列表
Type Car有int属性Id.
有一个答案,已经删除说
我的意思是说效率更高:更少的代码,更少的机制和更具可读性的案例
所以这样思考我的情况是什么?
什么是更少的代码,更少的机制,更可读的案例?
您可以使用以下情况:
var currentCarsNotInNewCars = currentCars.Except(newCars); var newCarsNotInCurrentCars = newCars.Except(currentCars);
但是,与foreach解决方案相比,这没有任何性能优势.它看起来更干净.
此外,请注意,您需要实现IEquatable<T>对于您的Car类,因此比较是在ID而不是在引用上完成的.
从表面上讲,更好的方法是不使用List<T>.但字典<TKey,TValue>以ID为关键:
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);
翻译自:https://stackoverflow.com/questions/6680487/c-sharp-more-efficient-way-of-comparing-two-collections
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Programming in Haskell
Graham Hutton / Cambridge University Press / 2007-1-18 / GBP 34.99
Haskell is one of the leading languages for teaching functional programming, enabling students to write simpler and cleaner code, and to learn how to structure and reason about programs. This introduc......一起来看看 《Programming in Haskell》 这本书的介绍吧!