C# 如何从子类型元素列表派生父类型元素列表?
我已经搜索了很长一段时间,但没有成功地从子类型元素列表派生父类型元素列表。 父类型包含持久数据,子类型添加一些我以后不需要的临时数据 因此,我希望仅保留父类型的属性,并删除子类型的其他属性,如以下示例所示:C# 如何从子类型元素列表派生父类型元素列表?,c#,list,parent-child,C#,List,Parent Child,我已经搜索了很长一段时间,但没有成功地从子类型元素列表派生父类型元素列表。 父类型包含持久数据,子类型添加一些我以后不需要的临时数据 因此,我希望仅保留父类型的属性,并删除子类型的其他属性,如以下示例所示: public class MainPage { public class Parent { public string ParentProperty; } public class Child : Parent { p
public class MainPage
{
public class Parent
{
public string ParentProperty;
}
public class Child : Parent
{
public string ChildProperty;
}
public static List<Child> listChild = new List<Child> {
new Child { ParentProperty = "ABC", ChildProperty = "XYZ"},
new Child { ParentProperty = "DEF", ChildProperty = "UVW"}
};
public void SomeFunction()
{
List<Parent> listParent = GetParentList(listChild);
//listParent should contain 2 elements, each with only 1 property containing "ABC" and "DEF" respectively...
}
public List<Parent> GetParentList(List<Child> listchild)
{
return listchild.????????; //what should I include here ???
}
}
public类主页
{
公共类父类
{
公共字符串属性;
}
公共类子级:父级
{
公共财产;
}
公共静态列表listChild=新列表{
新的子对象{ParentProperty=“ABC”,ChildProperty=“XYZ”},
新建子项{ParentProperty=“DEF”,ChildProperty=“UVW”}
};
公共函数()
{
List listParent=GetParentList(listChild);
//listParent应该包含2个元素,每个元素只有1个属性分别包含“ABC”和“DEF”。。。
}
公共列表GetParentList(列表子项)
{
返回listchild.??????;//这里应该包含什么内容???
}
}
我的所有尝试,如return(listchild作为列表)代码>给我列表中的子元素,即带有ChildProperty“XYZ”和“UVW”,这会使我的其余代码失败
谢谢你的想法 这将为您提供子实例作为父引用的表示:
public List<Parent> GetParentList(List<Child> listchild)
{
return listchild.Cast<Parent>().ToList();
}
public List GetParentList(List listchild)
{
返回listchild.Cast().ToList();
}
如果确实希望父实例具有与子实例相同的数据,则必须创建新实例并复制数据:
public List<Parent> GetParentList(List<Child> listchild)
{
return listchild.Select(child => new Parent{ ParentProperty = child.ParentProperty }).ToList();
}
public List GetParentList(List listchild)
{
返回listchild.Select(child=>newparent{ParentProperty=child.ParentProperty}).ToList();
}
返回listchild.Cast().ToList()
顺便说一句,您不会以这种方式删除任何子属性。。。它们仍然存在,你们可以把它们扔给孩子……谢谢你们。您的第一个建议确实可以正确编译,但只要我想在序列化程序中使用列表
,我就会收到一个错误,因为它找到了ChildProperty,这在父级定义中是未知的。我喜欢您的第二个建议:-)是否有一种简单的方法可以一次复制所有父级属性,还是我真的需要把它们一一列出?@Daniel你似乎有点问题。也许你应该问你的问题,而不是你认为的解决方案。是否要将子类序列化为父类?序列化是挑战之一,是的,因为它必须发生在父类中(父类在多个项目之间共享,并且只有一个项目知道子类)。因此,我需要剥离子属性。如果你知道我能读到一些关于这个主题的文章,我会很高兴得到这些信息。干杯