Merge and Update Two Lists in C#

后端 未结 6 1221
一生所求
一生所求 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条回答
  •  -上瘾入骨i
    2021-01-18 08:15

    I would probably use a dictionary rather than a list:

        // sample data
        var original = new Dictionary();
        for (int i = 1; i <= 10; i++)
        {
            original.Add(i, null);
        }
        var updated = new Dictionary();
        updated.Add(2, 67);
        updated.Add(4, 90);
        updated.Add(5, 98);
        updated.Add(11, 20); // add
    
        // merge
        foreach (var pair in updated)
        {
            original[pair.Key] = pair.Value;
        }
    
        // show results
        foreach (var pair in original.OrderBy(x => x.Key))
        {
            Console.WriteLine(pair.Key + ": " + pair.Value);
        }
    

    If you are talking about properties of an object, it will be trickier, but still doable.

提交回复
热议问题