Merge and Update Two Lists in C#

后端 未结 6 1224
一生所求
一生所求 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:56

    If you have both lists sorted by ID, you can use a variation of the classical merge algorithm:

    int pos = 0;
    foreach (var e in list2) {
      pos = list1.FindIndex(pos, x => x.Id==e.Id);
      list1[pos].Value = e.Value;
    }
    

    Note that this also requires list2 to be a strict subset of list1 in terms of ID (i.e. list1 really contains all ids of list2)

    Of course you can also wrap this in an extension method

    public static void UpdateWith(this List list1, List list2) 
    where T:SomeIdValueSupertype {
      int pos = 0;
      foreach (var e in list2) {
        pos = list1.FindIndex(pos, x => x.Id==e.Id);
        list1[pos].Value = e.Value;
      }
    }
    

提交回复
热议问题