如何从子类型元素列表中导出父类型元素列表?
How to derive a list of Parent type elements from a list of Child type elements?
我已经搜索了很长时间但没有成功,如何从子类型元素列表中导出父类型元素列表。
Parent 类型包含持久数据,而 Child 类型添加一些我以后不需要的瞬态数据。
因此我想只保留 Parent 类型的属性并删除 Child 类型的其他属性,如下例所示:
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 ???
}
}
我所有的尝试都像 return (listchild as List<Parent>);
在我的列表中给我子元素,即使用 ChildProperty "XYZ" 和 "UVW",这使我的其余代码失败...
感谢您的想法!
这将为您提供子实例作为父引用的表示:
public List<Parent> GetParentList(List<Child> listchild)
{
return listchild.Cast<Parent>().ToList();
}
如果您真的想要拥有与子实例具有相同数据的父实例,您将必须创建新实例并复制您的数据:
public List<Parent> GetParentList(List<Child> listchild)
{
return listchild.Select(child => new Parent{ ParentProperty = child.ParentProperty }).ToList();
}
我已经搜索了很长时间但没有成功,如何从子类型元素列表中导出父类型元素列表。 Parent 类型包含持久数据,而 Child 类型添加一些我以后不需要的瞬态数据。
因此我想只保留 Parent 类型的属性并删除 Child 类型的其他属性,如下例所示:
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 ???
}
}
我所有的尝试都像 return (listchild as List<Parent>);
在我的列表中给我子元素,即使用 ChildProperty "XYZ" 和 "UVW",这使我的其余代码失败...
感谢您的想法!
这将为您提供子实例作为父引用的表示:
public List<Parent> GetParentList(List<Child> listchild)
{
return listchild.Cast<Parent>().ToList();
}
如果您真的想要拥有与子实例具有相同数据的父实例,您将必须创建新实例并复制您的数据:
public List<Parent> GetParentList(List<Child> listchild)
{
return listchild.Select(child => new Parent{ ParentProperty = child.ParentProperty }).ToList();
}