0

I have got column in db which saves the string as 1,2,3,4,5 I want to separate the string to 1 2 3 4 5 and save each number in the array , for instance the array should be like int [] numbers , int[0] = 1 , int[1] = 2 ......

1
  • Which aspect of this question do you consider to be specific to ASP.NET? Commented Aug 4, 2011 at 12:40

3 Answers 3

3

Looks like you want:

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

Obviously this will go bang if any of the split results is not a parsable integer.

(You may also want to use a List<int> instead of an array, as a generally more flexible collection type.)

EDIT: Short but complete demo program:

using System;
using System.Globalization;
using System.Linq;

public class Test
{
    static void Main()
    {
        string eventIds = "1,2,3";
        int[] array =
            eventIds.Split(',')
                    .Select(x => int.Parse(x, CultureInfo.InvariantCulture))
                    .ToArray();
        foreach (int id in array)
        {
            Console.WriteLine(id);
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

i tried ur code with no success , the array is null , the values which i passed was 1,2,3
string EventIds = voucher.EventIDs; int[] array = EventIds.Split(',') .Select(x => int.Parse(x, CultureInfo.InvariantCulture)) .ToArray();
@Mr A: That code will never return a null reference. It's hard to say exactly what you're doing wrong, but I'll edit my answer with a short but complete program demonstrating it working.
1

here is code

Dim str as String = "1,2,3,4,5"

dim objstr() as String = str.split(",")

here split return array.

Comments

1

Here's a "safer" version of John's excellent code snippet that will deal with values that cannot be parsed as int by adding them as 0:

int temp;
int[] array = text.Split(',')
    .Select(x => int.TryParse(x, out temp) ? temp : 0)
    .ToArray();

If you want to be totally safe and discard any values that cannot be converted to an integer then you could use a function like this:

private static int[] ConvertTextToIntArray(string text)
{
    var integerList = new List<int>();
    var values = text.Split(',');
    int temp;

    foreach (var value in values)
    {
        if (int.TryParse(value, out temp))
        {
            integerList.Add(temp);
        }
    }

    return integerList.ToArray();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.