我有这将父集合的子集,以适当的父母映射方法应用子集匹配父母父集合的
public static void ApplyParentChild<TParent, TChild, TId>(
this IEnumerable<TParent> parents, IEnumerable<TChild> children,
Func<TParent, TId> id, Func<TChild, TId> parentId,
Action<TParent, TChild> action
)
{
var lookup = parents.ToDictionary(id);
foreach (var child in children)
{
TParent parent;
if (lookup.TryGetValue(parentId(child), out parent))
action(parent, child);
}
}
&这炒锅如果我叫下面的方法(有项目在它的阶段列表)
projects.ApplyParentChild(phases, p => p.ProjectId, c => c.ProjectId, (p, c) => p.ProjectPhases.Add(c));
但我经常会得到一个情况,我有一个阶段有项目引用。所以我把它叫做
phases.ApplyParentChild(projects, p => p.ProjectId, c => c.ProjectId, (p, c) => p.project=c);
这个失败。这是因为parents.ToDictionary(id)
未能获得唯一标识符并将错误返回为“已添加具有相同密钥的项目”。
我该如何处理这个问题?我不是一个linq大师。谁能帮我吗 ?
有没有什么好的理由说明你(很差)重新实现Linq连接? – spender
HW是一个linq连接? –