David
David

Reputation: 632

Specified cast is not valid when trying to iterate through an IEnumerable<int> in C#

so I am currently learning LINQ in C# and I was trying this Cast<> extension method which doesn't really seem to work out. When I try to iterate through the IEnumerable<int> values, it doesn't work it gives me the error :

System.InvalidCastException("Specified cast is not valid").

This is the code: (I've also tried to cast the 'result' variable into an array with ToArray() but it still didn't work, regardless of what I tried)

List<string> strings = new List<string>(){ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10 };
IEnumerable<int> result = strings.Cast<int>();

foreach(int number in result){
    Console.WriteLine(number);
}

Console.ReadKey();

I've also tried to use 'var' instead of 'int' when trying to iterate through the IEnumerable result variable but it still doesn't work out, Here is an image of what it shows me:

enter image description here

Upvotes: -1

Views: 2029

Answers (2)

smolchanovsky
smolchanovsky

Reputation: 1863

You should use int.TryParse instead. So you can implement cast this way:

strings
    .Select(x => int.TryParse(x, out var result) ? result : 0)
    .ToArray()

or

strings
    .Select(x => int.TryParse(x, out var result) ? result : throw new InvalidCastException(message: ""))
    .ToArray()

Upvotes: 1

Allen Chen
Allen Chen

Reputation: 226

Cast is not for the value type casting, you cannot convert string to int by using Cast, this method is used to convert some array types that don't implement IEnumerable, e.g. ArrayList. So that you cannot use LINQ with ArrayList. If you want to query the ArrayList with LINQ syntax, you can use Cast to transform ArrayList into Enumerable, then the LINQ query is available. Please refer to the official document

Upvotes: -1

Related Questions