Reputation: 1085
How to cast two List...
I want something like that
List<Obj1> list = new List<Obj1>();
list.add(new Obj1);
List<Obj2> list2 = new List<Obj2>();
list2.add((Obj1)list[0]);
Upvotes: 2
Views: 384
Reputation: 38590
You may be interested in the Enumerable extension method Cast.
IEnumerable<Obj2> enumerable = list.Cast<Obj2>();
You can then convert to List
if necessary:
var list2 = enumerable.ToList()
(This obviously assume the cast from Obj1
to Obj2
is valid: that Obj2
derives from Obj1
or that a conversion operator exists.)
Upvotes: 5
Reputation: 31428
I'm not sure what you are trying to do but it might be something like this
var nums = new List<int> {3,1,4,1,5,9,2,6,5};
var words = new List<string> {"Do", "not", "disturb", "my", "circles"};
words.AddRange(nums.Cast<string>());
Upvotes: 1
Reputation: 42246
To add a single element, your code would work, provided you fix the syntax:
List<Obj1> list = new List<Obj1>();
list.Add(new Obj1());
List<Obj2> list2 = new List<Obj2>();
list2.Add((Obj1)list[0]);
To concatenate the the whole list you can replace the last line with list2.AddRange(list.Cast<Obj1>());
Upvotes: 0