Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to int array using LINQ [duplicate]

Tags:

c#

linq

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;
}
like image 825
OlimilOops Avatar asked Jun 02 '10 15:06

OlimilOops


6 Answers

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();
like image 179
JSprang Avatar answered Nov 08 '22 23:11

JSprang


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();
like image 44
Buginator Avatar answered Nov 08 '22 23:11

Buginator


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.

like image 35
Justin Niessner Avatar answered Nov 08 '22 23:11

Justin Niessner


Actually correct one to one implementation is:

int n;
int[] ia = s1.Split(';').Select(s => int.TryParse(s, out n) ? n : 0).ToArray();
like image 27
Jakub Šturc Avatar answered Nov 08 '22 23:11

Jakub Šturc


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);
like image 44
David Gladfelter Avatar answered Nov 09 '22 00:11

David Gladfelter


    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/

like image 42
Tathagat Verma Avatar answered Nov 08 '22 23:11

Tathagat Verma