Welcome to MSDN Blogs Sign in | Join | Help

How to Convert a list of Object/String to an Array Using LINQ?

This is something that I really like, I can convert a list of objects into an array of something.

I had a need to convert a list of string into an array of string, of course it can be done easily in several different ways, creating an array of int, converting the string element, and populate the int array, or using List<int> as container.

Using LINQ, is very simple.

string[] Origin = new string[] { "1", "2", "3", "4", "5" };
int[] Result = Origin.Select(item => Convert.ToInt32(item)).ToArray();

Less code to write. :)

Published Wednesday, March 19, 2008 12:05 AM by HelloWorld
Filed under: , ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: How to Convert a list of Object/String to an Array Using LINQ?

C# 2 has this as well -- Array.ConvertAll (and List<T> has a ConvertAll as well).

But yea, the LINQ extension methods are quite handy.

Also, "var" and array initializers make the first line a bit nicer:

var Origin = new[] { "1", "2", "3", "4", "5" };

Tuesday, March 18, 2008 11:06 PM by Michael Giagnocavo

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker