我有两个系列
List<Car> currentCars = GetCurrentCars();
List<Car> newCars = GetNewCars();
Run Code Online (Sandbox Code Playgroud)
我不想使用foreach循环或其他东西,因为我认为应该有更好的方法来做到这一点.
我正在寻找更有效的方法来比较这个集合并获得结果:
Type Car有int属性Id.
有一个答案,已经删除了说我的意思是说有效:更少的代码,更少的机制,更可读的案例
所以这样思考我的情况是什么?
什么是更少的代码,更少的机制,更可读的案例?
Rei*_*ica 13
你可以这样做:
// 1) List of cars in newCars and not in currentCars
var newButNotCurrentCars = newCars.Except(currentCars);
// 2) List of cars in currentCars and not in newCars
var currentButNotNewCars = currentCars.Except(newCars);
Run Code Online (Sandbox Code Playgroud)
该代码使用Enumerable.Except扩展方法(在.Net 3.5及更高版本中可用).
我相信这符合您的"更少的代码,更少的机制,更具可读性"的标准.
Dan*_*rth 11
你可以使用Except:
var currentCarsNotInNewCars = currentCars.Except(newCars);
var newCarsNotInCurrentCars = newCars.Except(currentCars);
Run Code Online (Sandbox Code Playgroud)
但是这对foreach解决方案没有任何性能优势.它看起来更干净.
另外,请注意您需要IEquatable<T>为您的Car类实现的事实,因此比较是在ID而不是在引用上完成的.
从表面上看,更好的方法是不使用ID List<T>而是Dictionary<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);
Run Code Online (Sandbox Code Playgroud)