在C#中,给出以下代码:

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


    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;

是否可以不带循环将sortedPeople的结果加载回List 中?

谢谢。

最佳答案

是的。有一个.ToList()扩展方法,因此您需要做的就是这样调用它。

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

现在sortedPeople将是List<Person>而不是IOrderedEnumerable<Person>

10-07 20:17