87

I have a function (tointarray) to convert a string into an array of ints, but I am not very satisfied with it. It does the job, but there must be a more elegant way to do this, and perhaps LINQ could help here. Unfortunately I am not very good in LINQ. Is there a better way?

My function:

{
    string s1 = "1;2;3;4;5;6;7;8;9;10;11;12";
    int[] ia = tointarray(s1, ';');
}
int[] tointarray(string value, char sep)
{
    string[] sa = value.Split(sep);
    int[] ia = new int[sa.Length];
    for (int i = 0; i < ia.Length; ++i)
    {
        int j;
        string s = sa[i];
        if (int.TryParse(s, out j))
        {
            ia[i] = j;
        }
    }
    return ia;
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
OlimilOops
  • 6,747
  • 6
  • 26
  • 36

6 Answers6

232

This post asked a similar question and used LINQ to solve it, maybe it will help you out too.

string s1 = "1;2;3;4;5;6;7;8;9;10;11;12";
int[] ia = s1.Split(';').Select(n => Convert.ToInt32(n)).ToArray();
Community
  • 1
  • 1
JSprang
  • 12,481
  • 7
  • 30
  • 32
41

You can shorten JSprangs solution a bit by using a method group instead:

string s1 = "1;2;3;4;5;6;7;8;9;10;11;12";
int[] ints = s1.Split(';').Select(int.Parse).ToArray();
Buginator
  • 846
  • 11
  • 18
19

Actually correct one to one implementation is:

int n;
int[] ia = s1.Split(';').Select(s => int.TryParse(s, out n) ? n : 0).ToArray();
Jakub Šturc
  • 35,201
  • 25
  • 90
  • 110
18
s1.Split(';').Select(s => Convert.ToInt32(s)).ToArray();

Untested and off the top of my head...testing now for correct syntax.

Tested and everything looks good.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • 1
    Can't you just do: `s1.Split(';').Select(Convert.ToInt32).ToArray();` – strager Jun 02 '10 at 15:37
  • 1
    @strager - No, that statement doesn't compile. – Justin Niessner Jun 02 '10 at 15:40
  • 1
    @strager, apparently you cannot to that using .Net 4.0. You are dreaming in Python ;) – Hamish Grubijan Jun 02 '10 at 15:40
  • Nah, I've been spending too much time with Javascript. =] – strager Jun 02 '10 at 15:54
  • 1
    It usually does work, since the method name will be cast to the correct Func/predicate/delegate. The reason it doesn't work with Convert.ToInt32 is because of the Convert(string,int) overload that confuses the type inference. `s1.Split(';').Select((Func)Convert.ToInt32).ToArray()` works correctly, but isn't really any less code – Mike Jun 02 '10 at 16:13
  • Anyway the given implementation isn't correct since unlike given sample it fail on inputs that contains non integer strings. – Jakub Šturc Jun 02 '10 at 16:33
  • @Jakub - Depending on how you truly want the code to function, this might be exactly what you're looking for. Not everybody wants arbitrary zeros in their results. – Justin Niessner Jun 02 '10 at 17:13
  • @Justin: Right, but I couldn't help myself. – Jakub Šturc Jun 03 '10 at 09:43
8

Here's code that filters out invalid fields:

    var ints = from field in s1.Split(';').Where((x) => { int dummy; return Int32.TryParse(x, out dummy); })
               select Int32.Parse(field);
David Gladfelter
  • 4,175
  • 2
  • 25
  • 25
  • +1 I kept scrolling trying to find the solution equivalent to the OPs code. Unfortunately this is less efficient since it has to parse the int twice. – xr280xr Jul 31 '15 at 20:42
1
    public static int[] ConvertArray(string[] arrayToConvert)
    {
        int[] resultingArray = new int[arrayToConvert.Length];

        int itemValue;

        resultingArray = Array.ConvertAll<string, int>
            (
                arrayToConvert, 
                delegate(string intParameter) 
                {
                    int.TryParse(intParameter, out itemValue);
                    return itemValue;
                }
            );

        return resultingArray;
    }

Reference:

http://codepolice.net/convert-string-array-to-int-array-and-vice-versa-in-c/

Tathagat Verma
  • 549
  • 7
  • 12