Take the 2-minute tour ×

I have a DB table that contains a comma separated list of ID's (ints) that are stored as nvarchar.

I have a get method to return these in one hit as a list. At the moment I think I'll have to do something like this:

string[] pageids = experssion.Split(separators)

foreach (string number in pageids)

Can anyone think of a nicer way to do this ? Can I do it all on the split somehow ?

share|improve this question
BTW: I don't get what is pageids variable good for. –  Jakub Šturc May 22 '09 at 15:07
to try and make the explanation clearer. I stupidly put the split on the foreach –  Jon Jones May 22 '09 at 15:15
this is why you shouldn't try to store multiple values in a single db field... it always comes back to haunt you. –  rmeador May 22 '09 at 15:20
add comment

3 Answers

up vote 10 down vote accepted

I'd to it like this:

var ids = expression.Split(separator).Select(s => int.Parse(s));

It uses the Linq extensions of .NET 3.0. As an alternative (saves one lambda), you could also do this which is arguably less readable:

var ids = expression.Split(separator).Select((Func<string, int>)int.Parse);
share|improve this answer
Good to see you answering again. –  Joel Coehoorn May 22 '09 at 15:05
@Joel: I do my best – but recently I've had very much to do … and that's not about to change. :-( –  Konrad Rudolph May 22 '09 at 15:06
thanks! just what I needed –  Jon Jones May 22 '09 at 15:12
add comment

If you're not using C# 3.0, or aren't a fan of LINQ, you could 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

public static int StringToInt(string s)
 return int.Parse(s);


Or, even simpler as per Konrad's suggestion:

int[] pageids = Array.ConvertAll<string,int>(expression.Split(separator),int.Parse);
share|improve this answer
You don't need the StringToInt wrapper: int.Parse can directly be made into a Converter object. But other than that, good alternative. –  Konrad Rudolph May 22 '09 at 15:16
add comment

With LINQ you can do this:

List<int> ids 
  = expression
  .Select(number => Convert.ToInt32(number))
share|improve this answer
add comment

Your Answer


