开发者

convert string[] to int?[]

how to co开发者_StackOverflow中文版nvert a string array to nullable integer array.


Well, the two aspects are:

  • How do you convert an array from one type to another?
  • How do you convert a string to a nullable int?

The first is simple - you can use Array.ConvertAll, passing in an Converter delegate. There's the LINQ way as well (x.Select(...).ToArray()), but that's slightly less efficient if you know you've got an array to start with and you want an array out of the other end 1.

The string to int? is probably best done in a method. You can do it in an anonymous function, but in this particular case I'd use a separate method. I rarely like to have to declare variables in an anonymous function.

public static int? TryParseInt32(string text)
{
    int value;
    return int.TryParse(text, out value) ? value : (int?) null;
}

To answer the comment, yes you need the cast 2.

or without the conditional:

public static int? TryParseInt32(string text)
{
    int value;
    if (int.TryParse(text, out value))
    {
        return value;
    }
    else
    {
        return null;
    }
}

Put them together like this:

string[] x = {"15", "10", "hello", "5" };        
int?[] y = Array.ConvertAll(x, TryParseInt32);

1 Array.ConvertAll is more efficient than x.Select().ToArray() because it has more information. It can create the final array immediately - no resizing is ever required. Calling Enumerable.ToArray() (with the result of Select()) doesn't have the same information, so it effectively has to add the results to a List<T> (potentially resizing several times along the way) and then usually resize at the end as well. (It doesn't actually use List<T> but the concepts are the same.) It's definitely worth knowing about the Select/ToArray solution, but I don't think it's actually any more readable than ConvertAll in this case, so you might as well use the more efficient form.

2 The reason you need the cast in the conditional is because the compiler doesn't know what type of "null" you really mean - but it knows it can't convert from null to an int. The type of the conditional expression has to be either the type of the second operand or the type of the third operand, and the other one has to be implicitly convertibly. By forcing the third operand to be of type int? here everything is fine - because you can implicitly convert from int to int?. Note that the compiler doesn't take the way you're using the expression to try to work out the type. Another alternative is to use new int?() instead of null.


By parsing and using Linq:

string[] input = { "1", "3", "x" }
var result = input.Select(
    s => { int i; return (int.TryParse(s, out i)) ? i : (int?) null; }).ToArray();

… but I grant that this is a bit cryptic. I wouldn’t use a lambda expression here. For clarity, this should belong to a proper function ParseNullableInt. Then you can call it like this:

var result = input.Select(ParseNullableInt).ToArray();


Edit: I removed the null/empty check because TryParse properly handles those cases by returning false.

string[] stringArray = ...;
int?[] nullableIntArray = Array.ConvertAll(stringArray,
    s =>
    {
        int value;
        if (!int.TryParse(s, out value))
            return default(int?);
        return (int?)value;
    });


One option would be this (I'm presuming that you want nulls for the values that were not integer values):

public static class StringArrayExtension
{
    public static int?[] ToNullableIntArray(this string[] array)
    {
        int?[] result = new int?[array.Length];
        for (int index = 0; index < array.Length; index++)
        {
            string sourceValue = array[index];
            int destinationValue;
            if (int.TryParse(sourceValue, out destinationValue))
            {
                result[index] = destinationValue;
            }
            else
            {
                result[index] = null;
            }
        }
        return result;
    }
}

usage:

string[] source = { "hello", "1", "3.1415", "20", "foo" };
int?[] dest = source.ToNullableIntArray();


You need to use int.TryParse:

    string[] s = { "123", "a", "45" };
    int?[] result = new int?[s.Length];
    for (int i = 0; i < s.Length; ++i)
    {
        int a;
        if (int.TryParse(s[i], out a))
            result[i] = a;
    }


List<int?> ints = new List<int?>();
foreach (string str in strs)
{
    int val;
    if (int.TryParse(str, out val))
    {
        ints.Add(val);
    }
    else { ints.Add(null); }
}
return ints.ToArray();


An integer array can not be null. In fact every element in Integer Array will have "0" by default.

Regarding Conversion

Create an Integer array of the same length or an arraylist

int [] _arr=new int[strArray.length];
for(int i=0;i<strArray.length;i++]
{
   if(String.IsNullOrEmpty(strArray[i]))
   {
       _arr[i]=0;
   }
   else
   {
       _arr[i]=int.Parse(strArray[i]);
   }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜