The other day I needed to convert the following string example "1,2,3,4,5" into an array of integers. What better way to accomplish this than to use LINQ. You can do this in one line with LINQ technology.
int[] nums = args[0].Split(',').Select( s => Convert.ToInt32(s) ).ToArray();
Here is the full code in a console app:
using
System;using
System.Collections.Generic;using
System.Linq;using
System.Text;namespace
StringToIntArray{
class Program{
static void Main(string[] args){
// convert a string to a list of integers int[] nums = args[0].Split(',').Select( s => Convert.ToInt32(s) ).ToArray(); Console.WriteLine(nums); Console.ReadLine();}
}
}

Thomas MorganPosted May 22, 2009, 4:39 PM
I found another solution similar here: http://www.mycodeshare.com/item.aspx?title=convert-string-integers-list-integers&itemid=1000000013
Matthew CochranPosted Jan 31, 2009, 10:53 AM
Nice sample Mike. It took me a while before I realized that "Select()" is really just a mapper method for enumerables. You could make your code even more readable with a few extension methods that are generic enough to be reusable. int[] nums = args[0].SplitAndConvertTo<Int32>(',', Convert.ToInt32); I have a base class library at work where we throw in useful non domain specific utility methods like this so they are available in all our projects. public static class Extensions { // Same as "Select()" but this syntax makes more sense to me public static IEnumerable<TOutput> Map<TInput, TOutput>(this IEnumerable<TInput> input, Func<TInput, TOutput> convert) { foreach(TInput item in input) yield return convert(item); } // Lets make it work on arrays public static TOutput[] MapArray<TInput, TOutput>(this TInput[] input, Func<TInput, TOutput> convert) { return input.Map(convert).ToArray(); //return input.Select(convert).ToArray(); // same thing } // specially for strings public static T[] SplitAndConvertTo<T>(this String value, char seperator, Func<String, T> convert) { return value.Split(seperator).MapArray(convert); } }