我试图利用’包含’来模拟旧的sql’,其中id为(1,2,3,4)’过滤查询的方式.
但是我在使用它时遇到了一些困难,因为我的身份处于更深层次.
码:
public class Category { public long Id { get; set; } public string Name { get; set; } } public class Characteristica { public Category Category { get; set; } public int Id { get; set; } public string Value { get; set; } } public class Person { public string Name { get; set; } public List<Characteristica> Appearance { get; set; } } class Program { static void Main(string[] args) { var persons = new List<Person> { new Person { Name = "Person A",Appearance = new List<Characteristica> { new Characteristica { Id = 22 },new Characteristica { Id = 5 },new Characteristica { Id = 12 } }},new Person { Name = "Person B",Appearance = new List<Characteristica> { new Characteristica { Id = 1 },new Characteristica { Id = 6 },new Characteristica { Id = 11 } }},new Person { Name = "Person C",Appearance = new List<Characteristica> { new Characteristica { Id = 2 },new Characteristica { Id = 8 },new Characteristica { Id = 13 } }},new Person { Name = "Person D",new Characteristica { Id = 10 } }},new Person { Name = "Person E",new Person { Name = "Person F",new Characteristica { Id = 23 } }},}; var listOfSearchedIds = new List<int> { 22,23 }; var selected = persons.Select(p => p.Appearance.Where(a => listOfSearchedIds.Contains(a.Id))).ToList(); } }
现在我试图通过使用contains feauture从我的收藏中获取’Person A’和’Person F’.但是我无法看到我在这里做错了什么.
解决方法
你的方式是正确的,但你应该使用Where而不是Select
var selected = persons.Where(p => p.Appearance .Where(a => listOfSearchedIds.Contains(a.Id)) .Any()).ToList();
并且您需要使用Any来检查p.Appearance.Where中的返回序列是否包含任何元素.或者您可以直接使用Any并使其更短:
var selected = persons.Where(p => p.Appearance .Any(a => listOfSearchedIds.Contains(a.Id)) .ToList();