合并和更新C#中的两个列表 [英] Merge and Update Two Lists in C#

查看:98
本文介绍了合并和更新C#中的两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个List<T>对象:

例如:

列表1:
ID,填充ID的值,值为空白,其中包含从1到10的ID.
1,"
2,"
...
10,"

List 1:
ID, Value where Id is populated and value is blank and it contains say IDs from 1 to 10.
1,""
2,""
...
10,""

列表2:
ID,Value和其他属性都用值填充,但是此列表是ID列表1的子集. (例如,只有3个项目)
2,67
4,90
5,98

List 2:
ID, Value and other attributes all filled with values but this list is a subset of List 1 in terms of IDs. (e.g only 3 items)
2,67
4,90
5,98

我想要的是合并列表1,但具有更新的值.有没有人有任何好的扩展方法可以执行此操作,或者有任何优雅的代码可以执行此操作.最终列表应为:

What I want is a merged list 1, but with updated values. Does anyone have any good extension method which will do this or any elegent code to perform this operation. The final list should be:

ID,值
1,"
2,67//来自列表2的值
3,"
4,90
5,98
6,"
...
10,"

ID, Value
1,""
2,67 //value from list 2
3,""
4,90
5,98
6,""
...
10,""

推荐答案

我可能会使用字典而不是列表:

I would probably use a dictionary rather than a list:

    // sample data
    var original = new Dictionary<int, int?>();
    for (int i = 1; i <= 10; i++)
    {
        original.Add(i, null);
    }
    var updated = new Dictionary<int, int>();
    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.

这篇关于合并和更新C#中的两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆