Best way to split and convert the result to ints
I have a DB table that contains a comma separated list of ids (ints) that are stored as nvarchar.
I have a get method that returns them in one hit as a list. At the moment I think I will need to do something like this:
List<int> ids = new List<int>();
string[] pageids = experssion.Split(separators)
foreach (string number in pageids)
{
ids.Add(Convert.ToInt32(number));
}
Can anyone think of a more convenient way to do this? Can I do it all on split?
+1
a source to share
3 answers
I would like this:
var ids = expression.Split(separator).Select(s => int.Parse(s));
It uses Linq extensions for .NET 3.0. Alternatively (saves one lambda) you can also do this, which is arguably less readable:
var ids = expression.Split(separator).Select((Func<string, int>)int.Parse);
+11
a source to share
If you are not using C # 3.0 or are not a LINQ fan, you can do it the C # 2.0 way:
// This gives you an int[]
int[] pageids = Array.ConvertAll(expression.Split(separator), new Converter<string,int>(StringToInt));
// Add each id to the list
ids.AddRange(pageids);
public static int StringToInt(string s)
{
return int.Parse(s);
}
EDIT:
Or, even simpler, as suggested by Konrad:
int[] pageids = Array.ConvertAll<string,int>(expression.Split(separator),int.Parse);
ids.AddRange(pageids);
+3
a source to share