简体   繁体   中英

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:

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

This will only succeed if all items can be cast and will throw a InvalidCastException otherwise.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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