How to separate string and save in the array in asp.net
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开发者_运维技巧 ......
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);
}
}
}
here is code
Dim str as String = "1,2,3,4,5"
dim objstr() as String = str.split(",")
here split return array.
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();
}
精彩评论