Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Convert LINQ var result to actual type

Tags:

c#

.net

linq

In c#, Given the following code:

public class Person
{
    public int PersonID { get; set; }
    public int Age { get; set; }
    public string Name { get; set; }
}

and

    List<Person> people = new List<Person>();

    for (int i = 0; i != 15; i++)
    {
        Person p = new Person();
        p.PersonID = i;
        p.Age = i * 12;
        p.Name = "Name " + i;
        people.Add(p);
    }


    var sortedPeople = from qPeople in people
                       where qPeople.Age > 0 && qPeople.Age < 25 || qPeople.Age > 100
                       orderby qPeople.Age descending
                       select qPeople;

Can I load the results of sortedPeople back into a List<Person> without a loop?

Thanks.

like image 945
DrBob Avatar asked Apr 14 '10 03:04

DrBob


3 Answers

Yes. There is a .ToList() extension method available, so all you would need to do is make a call to it like this.

var sortedPeople = (from qPeople in people 
                       where qPeople.Age > 0 && qPeople.Age < 25 || qPeople.Age > 100 
                       orderby qPeople.Age descending 
                       select qPeople).ToList(); 

Now sortedPeople will be a List<Person> instead of an IOrderedEnumerable<Person>

like image 137
Anthony Pegram Avatar answered Nov 15 '22 15:11

Anthony Pegram


You can use

sortedPeople.ToList()

Enumerable.ToList Method

Creates a List from an IEnumerable.

like image 23
Adriaan Stander Avatar answered Nov 15 '22 15:11

Adriaan Stander


 var sortedPeople = (from qPeople in people
                       where qPeople.Age > 0 && qPeople.Age < 25 || qPeople.Age > 100
                       orderby qPeople.Age descending
                       select qPeople).ToList();
like image 2
BFree Avatar answered Nov 15 '22 17:11

BFree