使用LINQ从列表中获取第一个和第二个对象

本文关键字:第一个 第二个 对象 获取 LINQ 列表 使用 | 更新日期: 2023-09-27 18:06:54

我有一个Person对象列表。如何使用LINQList<Person> People中得到满足一定条件的第一个和第二个Person对象?

假设这是我得到的列表。我怎样才能得到第一个和第二个超过18岁的人,那就是James和Jodie。

public class Person
{
    public string Name;
    public int age;
}
var People = new List<Person>
{
   new Person {Name = "Jack", Age = 15},
   new Person {Name = "James" , Age = 19},
   new Person {Name = "John" , Age = 14},
   new Person {Name = "Jodie" , Age = 21},
   new Person {Name = "Jessie" , Age = 19}
}

使用LINQ从列表中获取第一个和第二个对象

var topTwo = People.Where(a => a.Age > 18).Take(2).ToArray();
Person p1, p2;
if (topTwo.Any())
{
   p1 = topTwo[0];
   if (topTwo.Count > 1)
       p2 = topTwo[1];
}

您可以在这里使用'Take()'函数。

在您的例子中,下面的代码将获得前两个元素:

public class Person
{
    public string Name;
    public int age;
}
var People = new List<Person>
{
    new Person {Name = "Jack", Age = 15},
    new Person {Name = "James" , Age = 19},
    new Person {Name = "John" , Age = 14},
    new Person {Name = "Jodie" , Age = 21},
    new Person {Name = "Jessie" , Age = 19}
}
People.Take(2);

下面的代码将为您提供年龄为18的前2个元素:

public class Person
{
    public string Name;
    public int age;
}
var People = new List<Person>
{
    new Person {Name = "Jack", Age = 15},
    new Person {Name = "James" , Age = 19},
    new Person {Name = "John" , Age = 14},
    new Person {Name = "Jodie" , Age = 21},
    new Person {Name = "Jessie" , Age = 19}
}
People.Where(x => x.Age > 18).Take(2);
var firstTwo = People.Where(a => a.Age > 18).Take(2);
相关文章: