[英]What's the better way to write this linq query?
SQL : 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
My linq expression : 我的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();
My question: 我的问题:
The linq expression is too long, there is two 'select new' expressions, i wonder how to make it shorter? linq表达式太长,有两个'select new'表达式,我想知道如何缩短它?
What's the corresponding Extension Method to the linq query? linq查询的相应扩展方法是什么? How can i express the "from... from...where..." with Extension method? 如何用Extension方法表达“from ... from ... where ...”?
The first select new .. into x
I don't see why you need, try removing it and write group node by new...
第一个select new .. into x
我不明白为什么你需要,尝试删除它并写group node by new...
"from...from"
is written as a lambda expression like this: "from...from"
写成lambda表达式,如下所示:
Categories.SelectMany(n => Categories, (n, p) => new { Node = n, Parent = p });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.