0

我试图找出从列表中包含子列表的列表中进行选择的最有效方法。我有两节课:

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

然后我有一个方法:

       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
        }

我想返回每个项目都包含服务 3 作为服务的人员列表。我应该使用 SelectMany 还是 where 子句。我似乎无法做到正确。

4

2 回答 2

3

如果你把它拼出来,你应该在那里:找到所有拥有 id 为 3 的服务的人

return people.Where(p => p.Services.Any(s => s.Id == 3)).ToList();
于 2013-09-30T23:00:24.570 回答
1

您可以使用以下内容:

return people.Where(p => p.Services.Any(service => service.Id == 3)).ToList();
于 2013-09-30T23:01:18.293 回答