1

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> ?

Chris Hobbs
  • 745
  • 2
  • 9
  • 27
  • 1
    http://stackoverflow.com/questions/6201306/how-to-convert-liststring-to-listint has your solution – bill Jun 10 '15 at 17:23
  • 1
    "Cast is not valid" is not valid error. Please post complete compiler error along with CSXXXX error code. – Alexei Levenkov Jun 10 '15 at 17:23
  • `List` -> `List` is covered in linked duplicate and the `StringCollection` -> `List` covered in http://stackoverflow.com/questions/844412/convert-stringcollection-to-liststring (combine/refactor as needed) – Alexei Levenkov Jun 10 '15 at 17:26

1 Answers1

4

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.

Habib
  • 219,104
  • 29
  • 407
  • 436