我试图使用“contains”方法来模拟旧的SQL“where id in (1,2,3,4)”过滤查询的方式。
然而,当我的ID在更深层级时,使用它存在一些困难。
代码:
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", Appearance = new List<Characteristica> { new Characteristica { Id = 2 }, new Characteristica { Id = 5 }, new Characteristica { Id = 10 } }},
new Person { Name = "Person E", Appearance = new List<Characteristica> { new Characteristica { Id = 1 }, new Characteristica { Id = 8 }, new Characteristica { Id = 10 } }},
new Person { Name = "Person F", Appearance = new List<Characteristica> { new Characteristica { Id = 1 }, new Characteristica { Id = 6 }, 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特性从我的集合中取出“Person A”和“Person F”,但是我无法看出我在这里做错了什么。
有人可以指点一下我做错了什么吗?我已经尝试过不同版本的lambda表达式,但这是我能接近的最佳结果,但我从表达式中得到了所有6个项目。