tags:

views:

53

answers:

4

Using link what is the easiest way to convert a list of longs to a 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.

+5  A: 

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();
Daniel Renshaw
Yes, .Cast<> is the linq way to go.
asgerhallas
unaccepted. I got an invalid cast exception. I should have ran this before going to bed. The code below is an example of the exception. var a = new List<long>(); a.Add(5); a.Add(5); a.Add(5); a.Cast<int>().ToList();
acidzombie24
Actually if you add a value into a in your example it too will cause an exception.
acidzombie24
A: 
longList.Select( i => (int)i);

Nice and easy.

Jamiec
Not quite a List<int> ...
leppie
+1  A: 
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.

Charlie Somerville
+3  A: 

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();
leppie
I personally feel LINQ is better, as it'll work on any `IEnumerable`, not just `List<T>`. Although `ConvertAll()` is more backwards-compatible.
Charlie Somerville