我在c#
中有两个集合A: {
{id:4, name:"", age:1},
{id:3, name:"", age:3},
{id:2, name:"", age:5},
}
B: {
{id:2, name:"aa"},
{id:4, name:"bb"},
{id:3, name:"cc"},
}
我想根据集合B
填写集合A.A: {
{id:2, name:"aa",age:5},
{id:4, name:"bb",age:1},
{id:3, name:"cc",age:3},
}
我该怎么做? (我应该使用linq吗?)
我用过:
private static void FillIsCpHidden(ref Collection A)
{
var B= CollectionB.ToDictionary(item => item.id);
foreach (var item in A)
{
item.name= B[item.id].name;
}
}
答案 0 :(得分:4)
您可以从B
创建字典var dictB = B.ToDictionary(b=>b.id);
然后你创建一个新列表。
var c = A.Select(a=>new{ a.id, name=dictB[a.Id].name,a.age });
答案 1 :(得分:0)
我想让LINQ解决这个问题:
var d = (from i in A select new { id = i.id, age=i.age,
name = (from b in B where b.id == i.id select b.name).SingeleOrDefault()}).ToList();
不创建新变量的另一种可能性:
A = A.Select(d=>new{ d.id, name=a=>new{ a.id, name=dictB[a.Id].name,d.age})
答案 2 :(得分:0)
您可以尝试Linq
var collectionB = collectionA.Select(p=>new B() { id=p.id, name=p.name});
或
var collectionA = collectionB.Select(p=>new A() { id=p.id, name=p.name});
答案 3 :(得分:0)
您可以使用联接:
var result = a.Join(b,
o => o.Id,
i => i.Id,
(o, i) => new { o.Id, i.Name, o.Age });