简体   繁体   English

将子类集合转换为父类列表

[英]Converting child class collection to list of parent class

Within one of the pre-built class I have following scenario在其中一个预建课程中,我有以下场景

[Serializable, XmlInclude(typeof(Child1)), XmlInclude(typeof(Child2)), XmlRoot(IsNullable=false)]
public abstract class Parent
{

}

[Serializable, XmlRoot(IsNullable=false)]
public class Child1: Parent
{
    public string C1{get;set;}
}

[Serializable, XmlRoot(IsNullable=false)]
public class Child2: Parent
{
    public string C2{get;set;}
}

void Main()
{
    System.Collections.ObjectModel.Collection<object> Records = GetDataFromDb();
    //above line returns collection of object containing either Child1 or Child2 
    List<Parent> ToSet = null;//TODO: convert the child object collection to list of parent
}

how to convert the child class collection to list of parent class?如何将子类集合转换为父类列表?

You can use the System.Linq.Cast method:您可以使用System.Linq.Cast方法:

List<Parent> ToSet = Records.Cast<Parent>().ToList();

This will only succeed if all items can be cast and will throw a InvalidCastException otherwise.这只有在所有项目都可以投射时才会成功,否则将抛出InvalidCastException

Trivial.琐碎的。

System.Collections.ObjectModel.Collection<object> Records = GetDataFromDb();
//above line returns collection of object containing either Child1 or Child2 
List<Parent> ToSet = Records.OfType<Parent>().ToList();

Compared to Cast , it will not return instances that cannot be cast to Parent .Cast相比,它不会返回无法转换为Parent的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM