2

I want to to cast a list of object type A to a list of object type B, where A inherit B.

Concretely :

public class A : B
{
    public string name { get; set; }
}

public class B
{
    public B() { }
}

I parse a JSON string that I cast to my list of type A :

B elem = ((JArray)_configuration).ToObject<List<A>>();

And I have this error :

Cannot implicitly convert type 'System.Collections.Generic.List< A>' to 'System.Collections.Generic.List< B>'

I tried to cast it :

List<B> elem = (List<B>)((JArray)_configuration).ToObject<List<A>>();

but got this error :

Cannot convert type 'System.Collections.Generic.List< A>' to 'System.Collections.Generic.List< B>'

I couldn't find help, maybe because I don't know what to look for, so apologies if it has been answered somewhere already !

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
carndacier
  • 960
  • 15
  • 38

3 Answers3

2

You can use the Enumerable.Cast<>() for this.

List<B> list = myList.Cast<B>().ToList();

But the ToList() will create a copy. If you just want for iterate the items. Don't use the ToList() and handle it as an IEnumerable<B>. It will be cast lazy 'on-the-fly'

Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57
0

Ok, just found the answer if it can help. If not, tell me and I will remove the question. Sorry for that !

Just needed to do :

List<B> elem = new List<B>(((JArray)_configuration).ToObject<List<A>>());
carndacier
  • 960
  • 15
  • 38
0

maybe you should read this, use list.selectall.

you can also try this for arrays.

Community
  • 1
  • 1
LiranBo
  • 2,054
  • 2
  • 23
  • 39