简体   繁体   English

如何编写linq表达式以根据状态过滤导航属性?

[英]how to write linq expression to filter navigational property based on status?

parent category contains a list of sub categories and sub categories contains a list of sub categories. 父类别包含子类别列表,子类别包含子类别列表。 Now I want to fetch all parent categories if its status is true along with subcategories. 现在,我想获取所有父类别(如果其状态为true)以及子类别。 I want to check the subcategories status also while fetching. 提取时,我还要检查子类别的状态。 My current query is 我目前的查询是

 db.Categories.Where(x => x.Status)
.Include(x=>x.SubCategories)
. OfType<ParentCategory>().ToList(); 

how to check the status of subcategories in this query?? 如何在此查询中检查子类别的状态?

Try LINQ's SelectMany() method. 尝试LINQ的SelectMany()方法。 It is used to flatten nested collections. 它用于展平嵌套的集合。 Instead of using nested for loops, we can do the task in a more 'LINQ' way. 无需使用嵌套的for循环,我们可以以更“ LINQ”的方式完成任务。

Ex given below - 前例如下:

Master m1 = new Master() { name = "A", lstObj = new List<obj> { new obj { i = 1, s = "C++" }, new obj { i = 1, s = "C#" }, new obj { i = 1, s = "Java" } } };

Master m2 = new Master() { name = "A", lstObj = new List<obj> { new obj { i = 4, s = "PHP" }, new obj { i = 5, s = "Ruby" }, new obj { i = 6, s = "Perl" } } };

List<Master> lstMasters = new List<Master> { m1, m2 };
var result = lstMasters.SelectMany(m => m.lstObj).Where(o => o.s == "PHP");

Just replace the Master class with your own master class. 只需将Master类替换为您自己的Master类即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM