c# – 编写这个linq查询的更好方法是什么?
发布时间:2020-12-15 21:50:52 所属栏目:百科 来源:网络整理
导读: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 LeafFROM Article_Category AS no
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.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,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(); 我的问题: > linq表达式太长,有两个’select new’表达式,我想知道如何缩短它? 解决方法
第一个选择新..进入x我不明白为什么你需要,尝试删除它并写新的组节点…
“from … from”写成lambda表达式,如下所示: Categories.SelectMany(n => Categories,(n,p) => new { Node = n,Parent = p }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |