Cast StringCollection as List<int>

1.8k Views Asked by At

I have a StringCollection object being passed through a ReportParameter object, and I need to get it to be a List<int> instead.

So far, I've tried this

List<int> ids = (parameters != null) ? parameters[parameters.FindIndex(x => x.Name == "IDs")].Values.Cast<int>().ToList() : null;

Which should check if the parameters object is null, and if not it finds the index of the IDs parameter, and then tries to cast the values to a list of ints. I keep getting a Cast is not valid error. How would I go about converting the StringCollection to List<int> ?

1

There are 1 best solutions below

0
On BEST ANSWER

They are string values, you can't cast string to int. You need to Convert/Parse it like:

parameters[parameters.FindIndex(x => x.Name == "IDs")].Values
                     .Cast<String>() //So that LINQ could be applied
                     .Select(int.Parse)
                     .ToList() 

You need .Cast<String>() so that you can apply LINQ on the StringCollection.