10

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?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Jimbo
  • 22,379
  • 42
  • 117
  • 159

5 Answers5

13
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?).

spender
  • 117,338
  • 33
  • 229
  • 351
  • 11
    you can simplify, btw; `Request["ID"].Split(',').Select(int.Parse).ToArray();`, or even `Array.ConvertAll(Request["ID"].Split(','), int.Parse)` – Marc Gravell May 26 '11 at 12:26
2

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(','));
Albin Sunnanbo
  • 46,430
  • 8
  • 69
  • 108
2
int[] ids = Request["ID"].Split(',').Select(Convert.ToInt32).ToArray();
Andreas Grech
  • 105,982
  • 98
  • 297
  • 360
1

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:

Community
  • 1
  • 1
abatishchev
  • 98,240
  • 88
  • 296
  • 433
0

If you don't have linq, you can:

string[] ids = Request["ID"].Split(',');
int[] items = new int[ids.Length];
for(int i = 0; i<ids.Length; i++)
{
  items[i] = int.Parse(ids[i]);
}
Valentin V
  • 24,971
  • 33
  • 103
  • 152