Linq加入两个类似的对象列表?

时间:2015-11-02 11:20:21

标签: c# linq

objA = new obj()
{
    ID = 123,
    attriA = "",
    attriB = "someValueB"
}

objB = new obj()
{
    ID = 123,
    attriA = "someValueA",
    attriB = ""
}

List<obj> ListA = new List<obj>();
ListA.add(objA);

List<obj> ListB = new List<obj>();
ListB.add(objB);

鉴于上述情况,我需要listC以下对象:

objC = new obj()
{
    ID = 123,
    attriA = "someValueA",
    attriB = "someBalueB"
}

这是我尝试过的。它有效,但我认为必须有办法缩短代码,使用linQ我不知道:

foreach(obj item in ListA)
{
    obj objB = ListB.Where(x=> x.ID == item.ID).FirstOrDefault();

    obj objC = new obj(){
        ID = objB.ID;
        attriA = item.attriA;
        attriB = objB.attriB;
    };
    ListC.add(objC);
}

2 个答案:

答案 0 :(得分:6)

您可以使用linq join,如下所示

 var query = from a in ListA
                join b in ListB
                     on a.ID equals b.ID
                select new Obj()
                {
                     ID = b.ID;
                attriA = a.attriA;
             attriB = b.attriB;
                };

以上代码未经过测试

答案 1 :(得分:4)

如果总有字符串,你可以用这样的东西:

var listC = ListA.Join(ListB, 
            A => A.ID, B => B.ID, 
            (A, B) => new {
                ID = A.ID,
                attriA = !string.IsNullOrEmpty(A.attriA) ? A.attriA : B.attriA,
                attriB = !string.IsNullOrEmpty(B.attriB) ? B.attriB : A.attriB
            });