Get the first and second objects from a list using LINQ
本问题已经有最佳答案,请猛点这里访问。
我有一份
假设这是我的清单。我怎样才能找到18岁以上的第一和第二个人,那就是詹姆斯和乔迪。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
1 2 3 4 5 6 7 8 9 | 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()'函数。
在您的情况下,以下代码将获得前2个元素:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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个元素:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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); |
。
1 | var firstTwo = People.Where(a => a.Age > 18).Take(2); |
号