0

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; }


}
Sanath Shetty
  • 484
  • 1
  • 7
  • 24

3 Answers3

4

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();
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
2

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

Community
  • 1
  • 1
Ankush Jain
  • 5,654
  • 4
  • 32
  • 57
1

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();
Farhad Jabiyev
  • 26,014
  • 8
  • 72
  • 98
  • I think it'll work fine. Just seems kind of non-obvious, but maybe my context is limited. – Trey Mack May 08 '14 at 05:37
  • I didn't downvote this, but I questioned it because it uses a feature in C# that *I believe* is fairly little-known, and the same thing can be achieved in the same number of lines with a constructor function, which *I believe* is more common. The *I believe*s are where I may be missing some context. Maybe this type of conversion is common in the OP's codebase. – Trey Mack May 08 '14 at 19:34
  • @tmack I didn't mean that the Downvoter was you. But, also why do you think that it is little-known? )) – Farhad Jabiyev May 09 '14 at 04:27