使用c#

时间:2015-07-14 07:51:13

标签: 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);
}

我要做的是将list2中的项目添加到list,如果它们具有相同的ID。因此,它应该将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"

有什么建议吗?

3 个答案:

答案 0 :(得分:3)

所以你需要在项目级别合并,而不是在列表级别合并。

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

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

答案 1 :(得分:1)

您必须使用自定义比较器:

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();

我尚未测试此代码。

答案 2 :(得分:0)

我认为你使用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;
}