views:

147

answers:

3

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:

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 nicer way to do this ? Can I do it all on the split somehow ?

+8  A: 

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);
Konrad Rudolph
Good to see you answering again.
Joel Coehoorn
@Joel: I do my best – but recently I've had very much to do … and that's not about to change. :-(
Konrad Rudolph
thanks! just what I needed
Jon Jones
+1  A: 

With LINQ you can do this:

List<int> ids 
  = expression
  .Split(separators)
  .Select(number => Convert.ToInt32(number))
  .ToList()
Jakub Šturc
+2  A: 

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
ids.AddRange(pageids);

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

EDIT:

Or, even simpler as per Konrad's suggestion:

int[] pageids = Array.ConvertAll<string,int>(expression.Split(separator),int.Parse);
ids.AddRange(pageids);
Winston Smith
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