.net – 包含lambda的C#linq表达式
发布时间:2020-12-16 03:48:06 所属栏目:百科 来源:网络整理
导读:我试图利用’包含’来模拟旧的SQL’,其中id为(1,2,3,4)’过滤查询的方式. 但是我在使用它时遇到了一些困难,因为我的身份处于更深层次. 码: public class Category { public long Id { get; set; } public string Name { get; set; } } public class Charact
我试图利用’包含’来模拟旧的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(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |