这个 LINQ 查询有更好的写法吗?

4

SQL:

SELECT node.CategoryId, 
    node.CategoryName, 
    node.Description, 
    node.Lft, node.Rgt, 
    node.ShowOnMenu,
 (COUNT(parent.CategoryName) - 1) AS Level, 
 (CASE WHEN node.Lft = node.Rgt - 1 THEN 'TRUE' ELSE 'FALSE' END) AS Leaf
FROM Article_Category AS node,
Article_Category AS parent
WHERE node.Lft BETWEEN parent.Lft AND parent.Rgt
GROUP BY node.CategoryId,node.CategoryName,node.Description,node.Lft,node.Rgt,node.ShowOnMenu
ORDER BY node.Lft

我的linq表达式:

        var list = (from node in DbContext.Categories
                    from parent in DbContext.Categories
                    where node.Lft >= parent.Lft && node.Lft <= parent.Rgt
                    select new
                    {
                        node.CategoryId,
                        node.CategoryName,
                        node.Description,
                        node.Lft,
                        node.Rgt,
                        node.ShowOnMenu,
                        ParentName = parent.CategoryName,
                    } into x
                    group x by new
                    {
                        x.CategoryId,
                        x.CategoryName,
                        x.Description,
                        x.Lft,
                        x.Rgt,
                        x.ShowOnMenu,
                    } into g
                    orderby g.Key.Lft
                    select new
                    {
                        CategoryId = g.Key.CategoryId,
                        CategoryName = g.Key.CategoryName,
                        Description = g.Key.Description,
                        Lft = g.Key.Lft,
                        Rgt = g.Key.Rgt,
                        ShowOnMenu = g.Key.ShowOnMenu,
                        Level = g.Count() - 1,
                        IsLeaf = g.Key.Lft == g.Key.Rgt - 1
                    }).ToList();

我的问题:

  1. linq表达式太长了,其中有两个“select new”表达式,我想知道如何使其更短?

  2. 与linq查询相对应的扩展方法是什么?我该如何使用扩展方法表示“from...from...where...”?

1个回答

1
第一个 select new..into x 我不认为你需要,尝试删除它并写成 group node by new... "from...from" 可以像这样写成 Lambda 表达式:
Categories.SelectMany(n => Categories, (n, p) => new { Node = n, Parent = p });

现在我的第一个问题已经解决了,我删除了第一个“select new”,它可以工作。但是我仍然不知道如何编写相应的扩展方法。我是否必须使用“(u, c)=>”表达式来选择我需要的所有属性,然后再次使用“GroupBy”、“OrderBy”和“Select new”?如果是这样的话,那就和我的第一个问题(两个“new”)一样了。 - RongieZeng
@RongieZeng 更新了答案,使用了您问题中的表格。 - Magnus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接