Home

LINQ and Arrays

     

Converting a LINQ Result to an Array or List

We have seen that a LINQ expression produces a list of values and, so far, the resulting list was stored in a variable created in a from clause. If you want, you can store the result of the LINQ expression in a specific (or external) variable. To support this, the IEnumerable interface provides the ToArray() and the ToList() methods. The syntax of the ToArray() method is:

public static TSource[] ToArray<TSource>(
	this IEnumerable<TSource> source;)

To store the results of an IEnumerable list in an array, declare the array variable and assign the resulting list to it. Here is an example:

IEnumerable<Student> pupils = from studs
                              in students
                              // orderby studs.LastName
                              //where studs.Gender == Genders.Female 
                              select studs;
Student[] attendees = pupils.ToArray();

foreach (var std in attendees)
{
    ListViewItem lviStudent = new ListViewItem(std.StudentNumber.ToString());

    lviStudent.SubItems.Add(std.FirstName);
    lviStudent.SubItems.Add(std.LastName);
    lvwStudents.Items.Add(lviStudent);
}

Instead of first creating the select list, then declaring an array variable, you can include the LINQ statement in parentheses and call the ToArray() method outside the closing parenthesis. Here is an example:

Student[] pupils = (from studs
                    in students
                    // orderby studs.LastName
                    // where studs.Gender == Genders.Female 
                    select studs).ToArray();

foreach (var std in pupils)
{
    ListViewItem lviStudent = new ListViewItem(std.StudentNumber.ToString());

    lviStudent.SubItems.Add(std.FirstName);
    lviStudent.SubItems.Add(std.LastName);
    lvwStudents.Items.Add(lviStudent);
}

Instead of storing the result of a LINQ statement into an array, you can store it in a collection. To support this, the IEnumerable interface is equipped with the ToList() method. Its syntax is:

public static List<TSource> ToList<TSource>(
	this IEnumerable<TSource> source);

This method follows the same rules as its counterpart the ToArray() method except that you must declare a List<> generic variable for it. Here is an example:

IEnumerable<Student> pupils = from studs
                              in students
                              // orderby studs.LastName
                              // where studs.Gender == Genders.Female 
                              select studs;
List<Student> attendees = pupils.ToList();

You can then use the List<> variable as you see fit.

 

Previous Copyright © 2010-2014, FunctionX Next