Possible Duplicate:
Puzzling Enumerable.Cast InvalidCastException
Why does
List<long> numbers = Enumerable.Range(1, 9999).Cast<long>().ToList();
fail with an InvalidCastException?
Possible Duplicate:
Puzzling Enumerable.Cast InvalidCastException
Why does
List<long> numbers = Enumerable.Range(1, 9999).Cast<long>().ToList();
fail with an InvalidCastException?
See this answer: Puzzling Enumerable.Cast InvalidCastException
In summary, Cast() works on the non-generic IEnumerable, which boxes each int as an Object. So, when the Cast is called it can only treat the elements as being of type Object, which cannot be cast to long.
The solution is to use Select to perform an explicit cast of each strongly-typed element:
var numbers = Enumerable.Range(1,9999).Select(i=>(long)i).ToList();