Question

i have two classes as below i need to cast list<child> to list<BM>

 public class Child
{


    [JsonProperty("name")]
    public string title { get; set; }
    public string type { get; set; }
    public string url { get; set; }
    public List<Child> children { get; set; }
}


 public class BM
{

    public string title { get; set; }
    public string type { get; set; }
    public string url { get; set; }
    public List<BM> children { get; set; }


}
Was it helpful?

Solution 3

You can also use Custom Type Conversions if you want to cast between custom types like that:

Class2 class2Instance = (Class2)class1Instance;

So all you need is to define explicit or implicit conversion function in your child class.

// Add it into your Child class
public static explicit operator BM(Child obj)
{
    BM output = new BM()
    {
          title = obj.title,
          type = obj.type,
          url = obj.url,
          children = obj.children.Select(x => BM(x)).ToList()
    };
    return output;
}

and then:

var result = source.Select(x => (BM)x).ToList();

OTHER TIPS

You can't cast it. You can create new list with all items transformed from one class to another, but you can't cast the entire list at once.

You should probably create a method which will transform Child into BM instance:

public static BM ToBM(Child source)
{
    return new BN() {
        title = source.title,
        type = source.type,
        url = source.url,
        children = source.children.Select(x => ToBM(x)).ToList()
    };
}

and then use LINQ to transform entire list:

var BMs = source.Select(x => ToBM(x)).ToList();

use automapper's DLL. You can read more about automapper at http://automapper.codeplex.com/wikipage?title=Lists%20and%20Arrays

List<BM> BMList= 
    Mapper.Map<List<Child>, List<BM>>(childList);

same question has been asked before Automapper copy List to List

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top