开发者

How to cast List<> in C#

开发者_JS百科

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]);


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.)


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>());


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>());

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜