C# 将子对象附加到父泛型方法

C# 将子对象附加到父泛型方法,c#,asp.net,linq,entity-framework,C#,Asp.net,Linq,Entity Framework,每个父对象都有一个Id每个子对象都有一个属性ParentId,该属性标识一个唯一的父对象,如child.ParentId==parent.Id每个父对象都有属性子对象 此方法将与parent.Id==child.ParentId匹配的子对象附加到每个parents-Children属性 private void AttachChildrenToParent(IEnumerable<dynamic> parents,

每个父对象都有一个Id每个子对象都有一个属性ParentId,该属性标识一个唯一的父对象,如child.ParentId==parent.Id每个父对象都有属性子对象

此方法将与parent.Id==child.ParentId匹配的子对象附加到每个parents-Children属性

private void AttachChildrenToParent(IEnumerable<dynamic> parents, 
                                           IEnumerable<dynamic> children)
{
    parents.GroupJoin(
        children,
        p => p.Id,
        c => c.ParentId,
        (p, cn) => new { Parent = p, Children = cn })
        .ToList().ForEach(x => x.Parent.Children = x.Children);
}
private void AttachChildrenToParent(IEnumerable parents,
(可数儿童)
{
parents.GroupJoin(
儿童
p=>p.Id,
c=>c.ParentId,
(p,cn)=>新的{Parent=p,Children=cn})
.ToList().ForEach(x=>x.Parent.Children=x.Children);
}
我的问题:

实际上,我没有属性名为“Parent”或“Children”的对象,而是有各种表示子-父关系的属性。所以我需要一个不编码属性名的泛型方法,我想为它调用这样的方法


有人能帮助疲惫的大脑解决这个问题吗?

我假设在调用这个函数时,您知道父/子关系属性是什么

然后我建议您使用委托(实际上是lambda)来解决这个问题。我会这样做的。您可能需要反复使用代码才能使其正常工作(我还没有对其进行测试),但希望它能帮助您找到解决方案

public delegate Guid GetProperty<T>(T obj);
        public delegate void AttachChildren<TParent, TChild>(TParent parent, IEnumerable<TChild> children);

        private void AttachChildrenToParent<TParent, TChild>(IEnumerable<TParent> parents, IEnumerable<TChild> children, GetProperty<TParent> getID, 
            GetProperty<TChild> getParentID, AttachChildren<TParent, TChild> attachObjects)
        {
            parents.GroupJoin(
           children,
           p => getID(p),
           c => getParentID(c),
           (p, cn) => new { Parent = p, Children = cn })
           .ToList().ForEach(x => attachObjects(x.Parent, x.Children)); 

        }

        private class Class1 { public Guid ID { get; set; } public IEnumerable<Class2> Children { get; set; } }
        private class Class2 { public Guid ID { get; set; } public Guid ParentID { get; set; } }
        private void test()
        {
            IEnumerable<Class1> lst1 = new List<Class1>();
            IEnumerable<Class2> lst2 = new List<Class2>();
            AttachChildrenToParent<Class1, Class2>(lst1, lst2, x => x.ID, x => x.ParentID, (x, y) => x.Children = y);
        }
public委托Guid GetProperty(T obj);
公共代表无效附加子女(t家长,i可数子女);
private void AttachChildrenToParent(IEnumerable parents、IEnumerable children、GetProperty getID、,
GetProperty getParentID,AttachChildren attachObjects)
{
parents.GroupJoin(
儿童
p=>getID(p),
c=>getParentID(c),
(p,cn)=>新的{Parent=p,Children=cn})
.ToList().ForEach(x=>attachObjects(x.Parent,x.Children));
}
私有类Class1{public Guid ID{get;set;}public IEnumerable子类{get;set;}
私有类Class2{public Guid ID{get;set;}public Guid ParentID{get;set;}
专用无效测试()
{
IEnumerable lst1=新列表();
IEnumerable lst2=新列表();
附件childrentoparent(lst1,lst2,x=>x.ID,x=>x.ParentID,(x,y=>x.Children=y);
}