C# 比较当前列表数据与旧列表数据
我必须将当前数据列表与以前的数据列表进行比较。在我的列表类中,我有C# 比较当前列表数据与旧列表数据,c#,C#,我必须将当前数据列表与以前的数据列表进行比较。在我的列表类中,我有 Id, Comment, Updatedby, Updated Dt, IsEdited 其他领域很少。我比较如下 foreach (var cscData in Currentcloses) { if (cscData.Status == ReferenceEnums.ActionStatus.EDIT) { if (Previoussoftcloses != null) {
Id,
Comment,
Updatedby,
Updated Dt,
IsEdited
其他领域很少。我比较如下
foreach (var cscData in Currentcloses)
{
if (cscData.Status == ReferenceEnums.ActionStatus.EDIT)
{
if (Previoussoftcloses != null)
{
foreach (var pscData in Previouscloses)
{
if (cscData.Id == pscData.Id)
{
//my logic goes here
}
}
}
}
}
除此之外还有更好的办法吗。我只是想看看
新代码
var currentData = Currentsoftcloses
.Where(c => c.Status == ReferenceEnums.ActionStatus.EDIT);
foreach (var cscData in currentData)
{
if (Previoussoftcloses != null)
{
var previous = Previoussoftcloses
.GroupBy(item => item.Id)
.ToDictionary(chunk => chunk.Key, chunk => chunk.First());
if (previous.TryGetValue(cscData.Id, out var pscData))
{
//my logic goes here
}
} }
你可以去掉内环;如果Previouscloses
较长,您的代码将更快:O(| Previoussoftcloses |+| Currentcloses |)
与O(| Previoussoftcloses |*| Currentcloses |)相比
时间复杂度
// If Previoussoftcloses == null we can do nothing, let's check for this possibility
if (Previoussoftcloses != null) {
// Dictionary is faster then List on Contains O(1) vs. O(N)
var previous = Previouscloses
.GroupBy(item => item.Id)
.ToDictionary(chunk => chunk.Key, chunk => chunk.First());
// Readability: what we are going to scan
var current = Currentcloses
.Where(c => c.Status == ReferenceEnums.ActionStatus.EDIT);
foreach (var cscData in current) {
if (previous.TryGetValue(cscData.Id, out var pscData)) {
//my logic goes here
}
}
}
以什么方式更好?更高效、更易读、更短?我认为这个问题属于codereview而不是stackoverflow。更有效的方法是你可以为你的类型覆盖Equals比较器,然后使用newList.Intersect(oldList)来接收differenceDmitry,,我已经更新了我的帖子。这是正确的方法吗?@Tronics:把你能做的一切都从循环中拉出来:看,如果
Previoussoftcloses==null
我们什么也做不了,我们会尽可能早地检查它;我们不想让computevar previous=Previoussoftcloses.GroupBy(…)
一次又一次地重复,让我们在循环之前完成它。