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.
|
|||||||||||||||||||