比较当前列表数据与旧列表数据

时间:2019-03-29 12:46:32

标签: c#

我必须将当前列表数据与上一个列表进行比较。在我的清单课程中,我有

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
                }
            } }

1 个答案:

答案 0 :(得分:1)

您可以摆脱内循环;如果Previouscloses long ,则您的代码将更快 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
    }
  }
}