Merge and Update Two Lists in C#

后端 未结 6 1285
一生所求
一生所求 2021-01-18 07:12

I have two List objects:

For example:

List 1:
ID, Value where Id is populated and value is blank and it contains s

6条回答
  •  没有蜡笔的小新
    2021-01-18 07:58

    This is O(m*n) but should do the job for arbitrary lists

            foreach (var record in List1)
            {
                var other = List2.FirstOrDefault(x => x.Key == record.Key);
                if(other != null) record.Value = other.Value;
            }
    

    If the lists are guaranteed ordered, then it could be brought down to O(n) at the cost of more code. The algortihm would be

    Current items start as head of each list
    While items remain in both lists
      If the current item of list1 has lower key than list2  advance to next in list1
      else if the current item of list2 has lower key than list1  advance to next in list2
      else copy value from current list2 item into list1 item and advance both lists.
    

提交回复
热议问题