gpt4 book ai didi

c# - 使用 C# 将通用列表项添加到另一个现有列表项

转载 作者:行者123 更新时间:2023-11-30 20:42:23 24 4
gpt4 key购买 nike

我有一个包含项目的通用列表。在此列表中,我有一列是唯一的(如 ID)。我还有另一个包含其他项目和相同 ID 列的通用列表。这是我将项目填充到列表中的方式:

foreach (string s in l1)
{
GridViewSource src = new GridViewSource();
src.test = "id" + s;

list.Add(src);
}

foreach (string s in l2)
{
GridViewSource src = new GridViewSource();
src.test = "id" + s;
src.test2 = "somerandomtext" + s;

list2.Add(src);
}

我想做的是将 list2 中具有相同 ID 的项目添加到 list 中。因此,它应该将 list2 中 ID 为“id3”的项目添加到 list 的项目“id3”中。喜欢合并。我不想将它们添加到列表底部或将它们插入项目之间。我尝试了 Concat 方法,但它只是将项目添加到列表的末尾:

list = list.Concat(list2).ToList();

编辑:

我尝试用另一种方式来解释它:

我的列表是这样的:

[0] => test = "id1", test2 = ""
[1] => test = "id2", test2 = ""
[2] => test = "id3", test2 = ""
[3] => test = "id4", test2 = ""
[4] => test = "id5", test2 = ""

我的 list2 看起来像这样:

[0] => test = "id1", test2 = "somerandomtext1"
[1] => test = "id2", test2 = "somerandomtext2"
[2] => test = "id3", test2 = "somerandomtext3"

当我合并列表时,它应该是这样的:

[0] => test = "id1", test2 = "somerandomtext1"
[1] => test = "id2", test2 = "somerandomtext2"
[2] => test = "id3", test2 = "somerandomtext3"
[3] => test = "id4", test2 = ""
[4] => test = "id5", test2 = ""

但它看起来像这样:

[0] => test = "id1", test2 = ""
[1] => test = "id2", test2 = ""
[2] => test = "id3", test2 = ""
[3] => test = "id4", test2 = ""
[4] => test = "id5", test2 = ""
[5] => test = "id1", test2 = "somerandomtext1"
[6] => test = "id2", test2 = "somerandomtext2"
[7] => test = "id3", test2 = "somerandomtext3"

有什么建议吗?

最佳答案

因此您需要在项目级别而不是列表级别进行合并。

我确信使用 Linq 有一些聪明的方法可以做到这一点,但我对 Linq 没有太多经验,所以我可以建议一个简单的嵌套 for 循环:

foreach (GridViewSource src1 in list1)
{
foreach(GridViewSource src2 in list2)
{
if(src1.test1 == src2.test1)
{
src1.test2 = src2.test2;
}
}
}

关于c# - 使用 C# 将通用列表项添加到另一个现有列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31400803/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com