【发布时间】:2014-11-22 01:48:03
【问题描述】:
(完整代码见:https://dotnetfiddle.net/tdKNgH)
我有两个由ParentName 关联的列表,我想以特定方式加入它们。
class Parent
{
public string ParentName { get; set; }
public IEnumerable<string> ChildNames { get; set; }
}
class Child
{
public string ParentName { get; set; }
public string ChildName { get; set; }
}
var parents = new List<Parent>()
{
new Parent() {ParentName = "Lee"},
new Parent() {ParentName = "Bob"},
new Parent() {ParentName = "Tom"}
};
var children = new List<Child>()
{
new Child() {ParentName = "Lee", ChildName = "A"},
new Child() {ParentName = "Tom", ChildName = "B"},
new Child() {ParentName = "Tom", ChildName = "C"}
};
我正在使用 foreach 循环加入,它可以工作,但是有更简洁的方法吗?
foreach (var parent in parents)
{
var p = parent; // to avoid foreach closure side-effects
p.ChildNames = children.Where(c => c.ParentName == p.ParentName)
.Select(c => c.ChildName);
}
生成的父母列表如下所示:
Parent Children
------ --------
Lee A
Bob (empty)
Tom B,C
【问题讨论】:
-
您可能需要考虑使用字典,如stackoverflow.com/questions/2101069/…
-
+1 表示字典方法(是的,就是你,Emmad),使代码更加不言自明。但是您拥有的代码实际上还可以。我什至认为它比其他“更优雅”的解决方案安全得多。
-
您可以将
foreach更改为parents.Select...:parents.Select (p => new Parent { ParentName = p.ParentName, ChildNames = children.Where (c => c.ParentName == p.ParentName).Select (c => c.ChildName) });。