2013-05-13 90 views
4

SQL寫這個linq查詢有什麼更好的方法?

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的表達太長,有兩個「選擇新的'表達,我想知道如何縮短它?

  2. linq查詢的相應擴展方法是什麼?如何使用擴展方法表達「從......哪裏......」?

回答

1

第一select new .. into x我不明白爲什麼你需要,請嘗試刪除它,並寫group node by new...

"from...from"寫成一個lambda表達式是這樣的:

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

好吧,我會試試吧,謝謝! – RongieZeng 2013-05-13 09:46:42

+0

現在我的第一個問題已解決,我刪除了第一個「選擇新的」,它的工作原理。但我仍然不知道如何編寫相應的擴展方法。我必須使用'(u,c)=>'表達式來選擇我需要的所有屬性,然後再次選擇'GroupBy','OrderBy'和'Select new'。如果這樣,這與我的第一個問題(兩個'新')是一樣的。 – RongieZeng 2013-05-13 10:07:59

+0

@RongieZeng更新了答案,以使用您提問的表格。 – Magnus 2013-05-13 11:08:36

相關問題