Tronics
Tronics

Reputation: 1490

comparing current list data with old list data

I have to compare current list of data with previous list of data. In my list class i have

Id, 
Comment, 
Updatedby, 
Updated Dt, 
IsEdited 

and few other fields. I am comparing like below.

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

Is there any better way other than this. Just want to check.

New Code

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

Upvotes: 2

Views: 92

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186813

You can get rid of inner loop; if Previouscloses is long, your code will be faster: O(|Previoussoftcloses| + |Currentcloses|) versus O(|Previoussoftcloses| * |Currentcloses|) time complexity.

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

Upvotes: 1

Related Questions