gpt4 book ai didi

c# - 编写此 linq 查询的更好方法是什么?

转载 作者:行者123 更新时间:2023-11-30 12:47:36 24 4
gpt4 key购买 nike

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查询对应的Extension Method是什么?我如何用扩展方法表达“从...从...哪里...”?

最佳答案

第一个 select new .. into x 我不明白你为什么需要它,尝试删除它并编写 group node by new...

"from...from" 写成这样的 lambda 表达式:

Categories.SelectMany(n => Categories, (n, p) => new { Node = n, Parent = p });

关于c# - 编写此 linq 查询的更好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16518198/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com