Wednesday, February 13, 2013

How to convert a list into array with Linq

In this post, I am going to explain how we can convert an generic list to simple int array with Help of Linq. Recently, I was working on an application and there I needed an Int array of for list of ids in generic list. I tried various methods and then with the help of ‘Select’ operator and ToArray method I have easily converted an generic list to the int array.

Lets take a simple example. I need a contact id list from a generic list of contacts and following is my contact class.

public class Contact
    public int ContactId { get; set; }
    public string Name { get; set; }

Now I have created a new GetContacts methods to create a new Generic List of Contacts.

private static List<Contact> GetContacts() {
    List<Contact> contacts=new List<Contact>();

    for (int i = 1; i <= 5; i++) {
        Contact contact=new Contact{ContactId = i,Name = string.Format("Name {0}",i)};

    return contacts;

Here is the main method for my console application.

static void Main() {
    List<Contact> contacts = GetContacts();
    int[] contactIds = contacts.Select(c => c.ContactId).ToArray();

    foreach (int contactId in contactIds) {

Here you can see with Select Operator and ToArray method I can easily convert a list into array. Let’s run the example

. How to convert list into array

Hope you like it. Stay tuned for more..

Shout it

kick it on


Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

Search This Blog
About Me
My Photo

Full Stack Developer,Blogger,Microsoft Mvp, Mentor, Life long learner, 10+ Years of Experience for JavaScript, web and Microsoft technologies. ASP.NET MVC,Web Forms,C#,AngularJs,Golang
Mvp profile
Subscribe to my blog

Enter your email address:

Follow us on facebook
Blog Archive
Total Pageviews