[英]List<T> add to T when id match
I have 2 lists of 2 different objects: 我有2个2个不同对象的列表:
public class A {
string Id;
string Name;
List<B> listofB;
}
public class B {
string Id;
string Test;
}
The Id in B
is the same as the Id in A
B
中的ID与A
的ID相同
now I have 2 lists 现在我有2个清单
var listA = new List<A>();
var listB = new List<B>();
How would you add every B
object where the Id's match to the list of A
via linq? 您如何通过linq将ID匹配的每个B
对象添加到A
列表中?
for now I did: 现在我做了:
foreach(var a in listA){
a.listofB = listB.FindAll(i => i.Id == a.Id);
}
But I would think there is a better way of doing this 但我认为有更好的方法
(This always returns null for now, still trying to figure out why) (这总是返回null,现在仍在试图找出原因)
But I would think there is a better way of doing this 但我认为有更好的方法
If that's working for you, why do you think that there's something better? 如果这对您有用,您为什么认为还有更好的选择? It's readable and probably efficient. 这是可读的,可能是有效的。
However, you could use Enumerable.Join
+ GroupBy
: 但是,您可以使用Enumerable.Join
+ GroupBy
:
var idGrps = from a in listA
join b in listB
on a.Id equals b.Id into bGroup
select new { a, bGroup };
foreach (var grp in idGrps)
{
grp.a.listofB = grp.bGroup.ToList();
}
But even if Join
is more efficient if the lists are large, it's not as readable. 但是即使列表很大,即使Join
效率更高 ,它也不容易阅读。 Maybe it's better to initialize the list from the A
-constructor from the start instead of maintaining two lists. 也许最好从一开始就从A
-constructor初始化列表,而不要维护两个列表。
You could use a GroupBy clause: 您可以使用GroupBy子句:
var theBsById = listB.GroupBy(b => b.Id);
and then: 接着:
foreach(IGrouping<int, B> grouping in theBsById)
{
A theA = listA.Where(a => a.Id == grouping.Key).FirstOrDefault();
if (theA != null)
{
theA.listofB = grouping.ToList();
}
}
(This would only update the listofBs in the As that have Ids in listB) (这只会更新列表中具有ID的As中的listB。)
or: 要么:
foreach(var a in listA)
{
a.listofB = theBsById
.Where(grouping => grouping.Key == a.Id)
.SelectMany(grouping => grouping)
.ToList();
}
(this would update the listofB for all As, which is what your code above does, too.) (这将更新所有As的listofB,这也是您上面的代码所做的。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.