我有一个Person
个对象的列表。如何使用Person
从List<Person> People
获取符合特定条件的第一个和第二个LINQ
个对象?
我们在这里说的是我得到的清单。我怎样才能得到18岁以上的第一和第二人詹姆斯和朱迪。
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}
}
答案 0 :(得分:4)
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];
}
答案 1 :(得分:2)
您可以使用&#39; Take()&#39;在这里发挥作用。
在您的情况下,以下代码将获得前两个元素:
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);
答案 2 :(得分:1)
var firstTwo = People.Where(a => a.Age > 18).Take(2);