[英]add generic list item to another existing list item using c#
我有一个充满物品的通用清单。 在此列表中,我有一栏是唯一的(如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);
}
我要尝试的是将具有相同ID的项目从list2
添加到list
。 因此,应将list2
中ID为“ id3”的项添加到list
的项“ id3”。 喜欢合并。 我不想将它们添加到列表的底部或将它们插入项目之间。 我尝试了Concat
方法,但它只是在添加项目的同时添加列表的末尾:
list = list.Concat(list2).ToList();
编辑:
我尝试用另一种方式解释它:
我的list
如下所示:
[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;
}
}
}
您必须使用自定义比较器:
public class MyComparer: IEqualityComparer<T>
{
public bool Equals(T o1,T o2)
{
// They are the same object
if (object.ReferenceEquals(o1, o2))
return true;
// They are not the same
if (o1 == null || o2 == null)
return false;
// They have the same ID
return o1.test1.Equals(o2.test1);
}
public int GetHashCode(X x)
{
return x.ID.GetHashCode();
}
}
然后在调用中使用它:
list = list.Union(list2, new MyComparer()).ToList();
我尚未测试此代码。
我认为您为此使用List<T>
处于错误的路径, Dictionary<K, V>
更适合这种情况。
然后,您可以执行以下操作:
dict[src.test] = src;
在第二个代码中,您需要在其中更新(或添加)项目:
GridViewSource outsrc;
if (dict.TryGetValue(src.test, out outsrc))
{
// items exists: update
outsrc.test2 = src.test2;
}
else
{
// item doesn't exist: add
dict[src.test] = src;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.