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

Using a link, what is the easiest way to convert a longs list to an ints list?

I need this to be a list, if it cannot be, maybe I would like to see a solution with an int array or some specific container f int.

+4
source share
4 answers

You do not need LINQ. Just do:

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

If you really want LINQ:

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

UPDATE : as some commentators note, the following answer is incorrect. As stated in the docs ,

If an item cannot be discarded for TResult input, this method will be an exception.

I suspect, but now I can’t verify that this means that everything that can be implicitly (for example, from int to long or a subtype to a supertype) will work, and everything else will throw an exception. In particular, even explicit casts (e.g., from long to int ) will fail.

/ UPDATE

You need to be aware of the possibility of data loss, as some of the lengths may have value outside the range supported by int.

  List<long> a = new List<long>(); List<int> b = a.Cast<int>().ToList(); 
+4
source
 var myIntList = myLongList.Select(x => (int)x).ToList(); 

It does not process long values ​​that exceed int , which can be executed correctly, although this does not actually happen.

+3
source
 longList.Select( i => (int)i); 

Nice and easy.

-2
source

Source: https://habr.com/ru/post/1308456/


All Articles