我试图找出从列表中包含子列表的列表中选择的最有效方法。 我有两个班:
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子句。我似乎无法做对。
答案 0 :(得分:3)
如果你说出来,你应该在那里: 找到所有拥有身份3
服务的人return people.Where(p => p.Services.Any(s => s.Id == 3)).ToList();
答案 1 :(得分:1)
您可以使用以下内容:
return people.Where(p => p.Services.Any(service => service.Id == 3)).ToList();