在 C# 中合并和更新两个列表

发布于 2024-08-02 02:43:28 字数 506 浏览 3 评论 0原文

我有两个 List 对象:

例如:

List 1:
ID,值,其中 Id 已填充且值为空,并且包含从 1 到 10 的 ID。
1、“”
2、“”
...
10、""

列表2:
ID、Value 和其他属性都填充了值,但该列表在 ID 方面是列表 1 的子集。 (例如只有 3 件商品)
2,67
4,90
5,98

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

ID、值
1、“”
2,67 //列表 2 中的值
3、“”
4,90
5,98
6、“”
...
10、“”

I have two List<T> objects:

For example:

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

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

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, Value
1,""
2,67 //value from list 2
3,""
4,90
5,98
6,""
...
10,""

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

帅哥哥的热头脑 2024-08-09 02:43:28

使用linq:list1=list2.Union(list1);

use linq: list1=list2.Union(list1);

预谋 2024-08-09 02:43:28

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

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

如果您正在谈论对象的属性,这会更棘手,但仍然可行。

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.

凝望流年 2024-08-09 02:43:28

这是 O(m*n) 但应该可以完成任意列表的工作

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

如果保证列表是有序的,那么它可以以更多代码为代价降低到 O(n)。 该算法将是

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.

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.
涙—继续流 2024-08-09 02:43:28

如果两个列表均按 ID 排序,则可以使用经典合并算法的变体:

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

请注意,这还要求 list2list1 的严格子集 就 ID 而言(即 list1 实际上包含 list2所有 id)

当然您也可以将其包装在扩展方法中

public static void UpdateWith<T>(this List<T> list1, List<T> 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;
  }
}

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<T>(this List<T> list1, List<T> 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;
  }
}
固执像三岁 2024-08-09 02:43:28
 private void btnSearch_Click(object sender, EventArgs e)
{
String searchBy = cmbSearchBy.Text.ToString();
String searchFor = txtSearchFor.Text.Trim();

var List3 = (from row in JobTitleDB.jobList
                         where (row.JID.ToString()+row.JobTitleName.ToString().ToLower()).Contains(searchFor.ToLower())
                         select row).ToList();
if (searchBy == "All")
            {
                dgJobTitles.DataSource = null;
                //dgJobTitles.DataSource = List1;
                //dgJobTitles.DataSource = List2;
                //dgJobTitles.DataSource = List1.Concat(List2);
                //dgJobTitles.DataSource = List1.Union(List2);
                dgJobTitles.DataSource = List3;
                //dgJobTitles.DataSource=List1.AddRange(List2);
            }
}
 private void btnSearch_Click(object sender, EventArgs e)
{
String searchBy = cmbSearchBy.Text.ToString();
String searchFor = txtSearchFor.Text.Trim();

var List3 = (from row in JobTitleDB.jobList
                         where (row.JID.ToString()+row.JobTitleName.ToString().ToLower()).Contains(searchFor.ToLower())
                         select row).ToList();
if (searchBy == "All")
            {
                dgJobTitles.DataSource = null;
                //dgJobTitles.DataSource = List1;
                //dgJobTitles.DataSource = List2;
                //dgJobTitles.DataSource = List1.Concat(List2);
                //dgJobTitles.DataSource = List1.Union(List2);
                dgJobTitles.DataSource = List3;
                //dgJobTitles.DataSource=List1.AddRange(List2);
            }
}
怕倦 2024-08-09 02:43:28
Dictionary<int, string> List1 = new Dictionary<int, string>();
List1.Add(1,"");
List1.Add(2,"");
List1.Add(3,"");
List1.Add(4,"");
List1.Add(5,"");
List1.Add(6,"");

Dictionary<int, string> List2 = new Dictionary<int, string>();
List2.Add(2, "two");
List2.Add(4, "four");
List2.Add(6, "six");

var Result = List1.Select(x => new KeyValuePair<int, string>(x.Key, List2.ContainsKey(x.Key) ? List2[x.Key] : x.Value)).ToList();
Dictionary<int, string> List1 = new Dictionary<int, string>();
List1.Add(1,"");
List1.Add(2,"");
List1.Add(3,"");
List1.Add(4,"");
List1.Add(5,"");
List1.Add(6,"");

Dictionary<int, string> List2 = new Dictionary<int, string>();
List2.Add(2, "two");
List2.Add(4, "four");
List2.Add(6, "six");

var Result = List1.Select(x => new KeyValuePair<int, string>(x.Key, List2.ContainsKey(x.Key) ? List2[x.Key] : x.Value)).ToList();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文