开发者

Using linq what is the easiest way to conv list<long> to list<int>?

开发者 https://www.devze.com 2022-12-28 22:30 出处:网络
Using link what is the easiest way to convert a list of longs to 开发者_如何学Goa list of ints?

Using link what is the easiest way to convert a list of longs to 开发者_如何学Goa list of ints?

I need it to be a list, if it cant be possibly i would like to see a solution with a int array or some kind f int container.


You dont need LINQ. Simply do:

List<int> intlist = longlist.ConvertAll(x => (int)x);

If you really do want LINQ:

var intlist = longlist.Select(x => (int) x).ToList();


UPDATE: as pointed out by some commenters, the following answer is incorrect. As stated in the docs,

If an element cannot be cast to type TResult, this method will throw an exception.

I suspect, but am unable to test right now, that this means anything that can be implicitly cast (e.g. int to long or subtype to supertype) will work while everything else will cause an exception. In particular, even explicit casts (e.g. long to int) will fail.

/UPDATE

You need to be aware of the possibility of data loss since some of the longs may have a value outside the range supported by an int.

        List<long> a = new List<long>();
        List<int> b = a.Cast<int>().ToList();


var myIntList = myLongList.Select(x => (int)x).ToList();

Doesn't handle long values larger than int can hold correctly, although there's not really any way around that.


longList.Select( i => (int)i);

Nice and easy.

0

精彩评论

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

关注公众号