The only way
Count()
or
ToList()
will throw an
InvalidCastException
is if you have a source list which contains values of different types, and you've used
Cast<SomeType>
to treat it as a list of a single type. *
List<object> source = new List<object>
{
42,
42L,
42F,
42M,
"42",
};
IEnumerable<long> items = source.Cast<long>();
items.Count();
items.ToList();
foreach (long value in items)
{
...
}
Demo[
^]
This is clearly described in the documentation of the
Cast
method:
Exceptions
InvalidCastException
An element in the sequence cannot be cast to type TResult
.
You can either filter the list to only include those items which are of the specified type:
IEnumerable<long> items = source.OfType<long>();
Or, if you're certain that all of the types in the list can be converted to the specified type, use a projection:
IEnumerable<long> items = source.Select(i => Convert.ToInt64(i));
* NB: This doesn't apply if the values all inherit from a base class and you use Cast<BaseClass>
, or they all implement an interface and you use Cast<TheInterface>
.