使用LINQ将其与其他列表进行比较时,如何在一个列表中设置值

时间:2015-02-03 13:08:34

标签: c# linq

我有两个清单:

List A                         List B

ID  FirstName  WorkingID       ID  FirstName  WorkingID
5   John       Null            5   John       1 
9   Patrick    Null            9   Patrick    2
16  Ryan       Null            16  Ryan       3

我想使用LINQ比较这些列表,如果两个列表中的ID相等,我想在第一个列表A列表中设置WorkingID。 感谢。

6 个答案:

答案 0 :(得分:5)

也是这样的:

A.ForEach(c => c.WorkingID = B.Where(m => m.ID == c.ID).Select(s => s.WorkingID).FirstOrDefault());

完整来源:

public class Test
{
    public int ID;
    public int? WorkingID;
}
class Program
{
static void Main(string[] args)
{
    var A = new List<Test>() 
    { 
        new Test { ID = 5, WorkingID = null }, 
        new Test { ID = 9, WorkingID = null }, 
        new Test { ID = 16, WorkingID = null }, 
        new Test { ID = 18, WorkingID = null } 
    };
    var B = new List<Test>() 
    { 
        new Test { ID = 5, WorkingID = 1 }, 
        new Test { ID = 9, WorkingID = 2 }, 
        new Test { ID = 16, WorkingID = 3 } 
    };

    A.ForEach(c => c.WorkingID = B.Where(m => m.ID == c.ID).Select(s => s.WorkingID).FirstOrDefault());
}
}

答案 1 :(得分:2)

试试这个:

listA.Where(a => listB.Any(b => a.ID == b.ID))
    .ToList()
    .ForEach(a => a.WorkingID = listB.First(b => b.ID == a.ID).WorkingID);

答案 2 :(得分:1)

 var query = from a in lista
             join b in listb on a.ID equals b.ID
             where b.WorkingID != null
             select new {a, b};
 foreach (var item in query)
 {
      item.a.WorkingID = item.b.WorkingID;
 }

很简单。

答案 3 :(得分:1)

您可以尝试这样的事情(不是纯粹的LINQ方法):

foreach(var item in listA)
{
    var itemInB = listB.FirstOrDefault(x=>x.ID==item.ID);

    if(itemInB!=null)
        item.WorkingID = itemInB.WorkongID

}

答案 4 :(得分:1)

这是一种方法,假设一个类结构如下:

class MyItem
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public int WorkingID { get; set; }
}

您可以加入匹配ID的第二个列表:

var list1 = new List<MyItem>() {
    new MyItem() { ID = 5, FirstName = "John" },
    new MyItem() { ID = 9, FirstName = "Patrick" },
    new MyItem() { ID = 16, FirstName = "Ryan" },
};

var list2 = new List<MyItem>() {
    new MyItem() { ID = 5, FirstName = "John", WorkingID = 1 },
    new MyItem() { ID = 9, FirstName = "Patrick", WorkingID = 2 },
    new MyItem() { ID = 16, FirstName = "Ryan", WorkingID = 3 },
};

var mergedList = from item1 in list1
                join item2 in list2
                on item1.ID equals item2.ID
                select new MyItem() { ID = item1.ID, FirstName = item1.FirstName, WorkingID = item2.WorkingID };

答案 5 :(得分:1)

我认为使用Join然后循环遍历列表会更有效率。以下几乎与Florian Schmidinger提供的答案相同:

A.AsEnumerable().Join(B.AsEnumerable(), a => a.ID, b => b.ID, (a, b) => new { a, b })
    .ToList().ForEach(obj => { obj.a.WorkingID = obj.b.WorkingID; });