c# - 有没有更好的方法来编写 LINQ 函数?
问题描述
所以,我是 LINQ 的新手,并试图弄清楚如何过滤项目。那是我的任务
public async Task<PagedList<Item>> GetItems (ItemParams itemParams) {
var items = _context.Items.AsQueryable ();
if (itemParams.CategoryId > 0) {
var category = GetCategory (itemParams.CategoryId);
items = items.Where (i => FilterItems (i, category.Result));
}
return await PagedList<Item>.CreatAsync (items, itemParams.PageNumber, itemParams.PageSize);
}
决定返回哪些项目的函数是
static bool FilterItems (Item item, Category category) {
if (item.CategoryId == category.Id) {
return true;
}
if (category.Children.Count > 0) {
foreach (Category cat in category.Children) {
return FilterItems (item, cat);
}
}
return false;
}
获取类别函数
public async Task<Category> GetCategory (int? id) {
if (id == null) {
return null;
}
var categories = _context.Categories.Include (x => x.Children).AsEnumerable ().Where (c => c.Id == id);
categories = Traverse (categories);
var category = await Task.FromResult (categories.First (c => c.Id == id));
return category;
}
解决方案
推荐阅读
- c# - 从大字符串中获取特定 URL
- python-3.x - 从 Python 中的子字符串中删除逗号
- c++ - 恢复作为模板给出的通用集合的类型
- sql - Oracle 正则表达式匹配最后一次出现的字符串
- flutter - Container 中的固定高度在 Flutter 中不起作用
- php - 循环 2 个差异表并在 XML 中输出结果
- microsoft-graph-api - Microsoft Graph API 获取 callRecord 方法:callRecord 的版本
- cockroachdb - 在 CockroachDB 中,我如何确定一个查询使用了多少内存?
- node.js - Bookshelfjs 在哪里和哪里销毁
- elasticsearch - 出现错误“未找到 [logdata.timestamp] 的映射以便排序”