开发者

How to convert this string to an array of integers?

开发者 https://www.devze.com 2023-01-15 23:36 出处:网络
I have string s = \"158,141,90,86\"; How I can convert them in开发者_JAVA技巧to int[]?int[] result = \"158,141,90,86\".Split(\',\').Select(int.Parse).ToArray();

I have string s = "158,141,90,86";

How I can convert them in开发者_JAVA技巧to int[]?


int[] result = "158,141,90,86".Split(',').Select(int.Parse).ToArray();


Like this, with LINQ:

int[] array = s.Split(',')
               .Select(x => int.Parse(x))
               .ToArray();

Note that that will throw an exception if any element of the text isn't an integer. If you want to make it more resilient (if this is user-entered data for example) you'll need to use int.TryParse; at that point life becomes a bit more complicated in terms of the LINQ query.

EDIT: To make it parse to an int?[] (with a null value corresponding to each invalid substring) you could do something like:

int?[] array = s.Split(',')
                .Select(x => { 
                      int value;
                      return int.TryParse(x, out value) ? value : (int?)null;
                 })
                .ToArray();

As I said, it's not terribly nice :(

EDIT: In the comments, Dan commented on the "obsession" with the above approach instead of (presumably) a more imperative approach. In my view even the less-pleasant second version is still easier to read than the imperative alternative. The ugliness is only due to the ugly nature of int.TryParse, which is no less ugly when used in imperative code.

If int.TryParse either returned int? or Tuple<bool, int> then it would be as easy as the first version. Even converting from the tuple form to the nullable form would be simple, with one extra projection:

int[] array = s.Split(',')
               .Select(x => int.TryParseTuple(x))
               .Select(tuple => tuple.First ? tuple.Second : (int?) null)
               .ToArray();


An imperative solution would of course be:

        string[] sa = s.Split(',');
        int?[] array = new int?[sa.Length];
        int value;
        for (int i = 0; i < sa.Length; i++)
            if (int.TryParse(sa[i], out value))
                array[i] = value;
            else
                array[i] = null;


Another solution with LINQ/int?[] is:

return source.Split(',') 
                .Select(x => {  
                      int? value = null; 
                      int parsed;
                      if (int.TryParse(x, out parsed)) {
                          value = parsed;
                      }
                      return value; 
                 }) 
                .ToArray();
0

精彩评论

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