Using LINQ to convert an array from one type to another

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();

}

}

}

Ebook Download
View all
Learn
View all