-1

I have a list of Person objects. How can I get the first and second Person objects that meet a certain criteria from List<Person> People using LINQ?

Let's say here is the list I've got. How can I get the first and second persons that are over 18 that is James and 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}
}
Vahid
  • 5,144
  • 13
  • 70
  • 146
  • @Red-arrower! The red-arrow is ridiculous! And to tell the truth I don't care one bit about the reputation. I'm here just for asking and learning :) – Vahid Jun 05 '14 at 09:24

3 Answers3

5
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];
}
David Pilkington
  • 13,528
  • 3
  • 41
  • 73
2

You can use the 'Take()' function here.

In your case, the following code will get the first 2 elements:

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);

The following code will get you the first 2 element with an age of 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}
}

People.Where(x => x.Age > 18).Take(2);
Complexity
  • 5,682
  • 6
  • 41
  • 84
1
var firstTwo = People.Where(a => a.Age > 18).Take(2);
PaulB
  • 23,264
  • 14
  • 56
  • 75