tags:

views:

482

answers:

3

What am I missing here?

I want to do a simple call to Select() like this:

List<int> list = new List<int>();  
//fill the list
List<int> selections = (List<int>)list.Select(i => i*i); //for example

And I keep having trouble casting it. What am I missing?

+5  A: 

Select() will return you an IEnumerable<int> type, you have to use the ToList() operator:

List<int> selections = list.Select(i => i*i).ToList();
CMS
+2  A: 

Select() doesn't return a List so of course you can't cast it to a list. You can use the ToList method instead:

list.Select(i => i*i).ToList();
cbp
While the answer is correct, I'm not sure the "of course" is valid... technically, the result of Select(...) **could** be a List<T> (masked as IEnumerable<T>). As it happens, it isn't, but that doesn't justify an "of course".
Marc Gravell
+2  A: 

As others have said, Select returns an IEnumerable<T> which isn't actually a list - it's the result of a lazily-evaluated iterator block.

However, if you're dealing with lists and you want a list back out with nothing other than a projection, using List<T>.ConvertAll will be more efficient as it's able to create the new list with the right size immediately:

List<int> selections = list.ConvertAll(i => i*i);

Unless you particularly care about the efficiency, however, I'd probably stick to Select as it'll give you more consistency with other LINQ code.

Jon Skeet