开发者

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 开发者_C百科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?


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


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(','));


int[] ids = Request["ID"].Split(',').Select(Convert.ToInt32).ToArray();


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()


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]);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜