首页 > 解决方案 > 有没有更好的方法来编写 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#linqasp.net-core-2.1

解决方案


您的过滤器将无法按预期工作,因为foreach在第一个循环中返回。名字FilterItems也不直观。

static bool ContainsItem(Category category, Item item)
{
    return
        category.Id == item.CategoryId ||
        category.Children.Any(c => ContainsItem(c, item);
}

由于 C# 对||执行短路评估 Operator,如果第一个匹配,则不会评估第二个术语。请注意,这不是一个肮脏的技巧,而是 C# 规范的一部分。


推荐阅读