user2623955
user2623955

Reputation: 175

Select from list with list as property

I am trying to figure out the most efficient way to select from a list where the list contains a sub list. I have two classes:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<Services> Services { get; set; }
}

public class Services
{
    public int Id;
    public string Name;
}

Then I have a method:

       public static List<Person> GetPeople()
        {
           List <Services> serviceList1 = new List<Services>();
           List <Services> serviceList2 = new List<Services>();
           var service = new Services
               {
                   Id = 1,
                   Name = "Service 1"
               };

           serviceList1.Add(service);

           service = new Services
               {
                   Id = 2,
                   Name = "Service 2"
               };
           serviceList1.Add(service);

           service = new Services
               {
                   Id = 3,
                   Name = "Service 3"
               };
           serviceList2.Add(service);

           service = new Services
               {
                   Id = 4,
                   Name = "Service 4"
               };
           serviceList2.Add(service);

           List<Person> people = new List<Person>();
           var person = new Person
               {
                   FirstName = "Bill",
                   LastName = "Murray",
                   Services = serviceList1
               };
           people.Add(person);

           person = new Person
           {
               FirstName = "Chevy",
               LastName = "Chase",
               Services = serviceList2
           };
           people.Add(person);

           return people //Where Service Id = 3
        }

I want to return the person list where each item includes Service 3 as a service. Should I be using SelectMany or a where clause. I just can't seem to get it right.

Upvotes: 0

Views: 72

Answers (2)

Simon Whitehead
Simon Whitehead

Reputation: 65049

You can use the following:

return people.Where(p => p.Services.Any(service => service.Id == 3)).ToList();

Upvotes: 1

ChrisWue
ChrisWue

Reputation: 19020

If you spell it out you should be pretty much there: Find all people who have a service with id 3

return people.Where(p => p.Services.Any(s => s.Id == 3)).ToList();

Upvotes: 3

Related Questions