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
  • 95,331
  • 80
  • 293
  • 426
Jimbo
  • 21,476
  • 39
  • 113
  • 157

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
  • 112,247
  • 30
  • 221
  • 334
  • 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
  • 45,452
  • 8
  • 67
  • 106
2
int[] ids = Request["ID"].Split(',').Select(Convert.ToInt32).ToArray();
Andreas Grech
  • 102,667
  • 98
  • 290
  • 358
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
  • 95,331
  • 80
  • 293
  • 426
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
  • 23,781
  • 31
  • 100
  • 148