Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse int[] from "1,2,3"

I have a multiselect dropdown called ID that submits ID=1,2,3 which I need parsed into an integer array to do a Contains() on in a filter method. At the moment I use:

string[] ids = Request["ID"].Split(',');

Which I don't really like because its slower to compare string than int. Any suggestions?

like image 835
Jimbo Avatar asked May 26 '11 12:05

Jimbo


4 Answers

Request["ID"].Split(',').Select(x=>int.Parse(x)).ToArray();

Of course, this will throw if any of the resulting numeric strings are not "parseable" (does such a word exist?).

like image 186
spender Avatar answered Nov 14 '22 06:11

spender


It depends on how many times you will look up in the array if converting to ints are faster or the string comparison is faster.

HashSet<int> ids = new HashSet<int>(from s in Request["ID"].Split(',')
                                    select int.Parse(s));

But probably the fastest if you have many id:s will be to create a HashSet<string>:

HashSet<string> = new HashSet<string>(string[] ids = Request["ID"].Split(','));
like image 27
Albin Sunnanbo Avatar answered Nov 14 '22 06:11

Albin Sunnanbo


int[] ids = Request["ID"].Split(',').Select(Convert.ToInt32).ToArray();
like image 32
Andreas Grech Avatar answered Nov 14 '22 05:11

Andreas Grech


First:

string[] arr = Request["ID"].Split(',')

Then:

Array.ConvertAll(arr, s => Int32.Parse(s));
Array.ConvertAll(arr, Int32.Parse);

arr.Select(s => Int32.Parse(s));
arr.Select(Int32.Parse);

Then:

new HashSet<int>(result);

(the most fast container to perform Contains())

See also:

  • Convert string[] to int[] in one string of code using LINQ
  • Which one is faster in processing and conversion int.Parse(), int.TryParse(), Convert.Int32()
like image 1
abatishchev Avatar answered Nov 14 '22 07:11

abatishchev