2012-04-13 33 views
0

我想分組,並仍然檢索表中的所有數據。我對Linq還很陌生,似乎無法告訴我做錯了什麼。我不僅想對結果進行分組,而且還想檢索表格中的所有列。這可能嗎?返回完整結果linq分組查詢

(from r in db.Form 
    orderby r.CreatedDate descending 
    group r by r.Record into myGroup 
    where myGroup.Count() > 0 
    where (r.CreatedDate > lastmonth) 
    where r.Name == "Test Name" 
    select new { r, myGroup.Key, Count = myGroup.Count() } 
    ) 

一些如何「r」失去其上下文或自從我分組「r」它已被替換。不確定。

回答

1

您需要將任務分成兩個步驟來完成你想要的。

組數據

var groupedData = db.Form.Where(item=>item.CreatedDate > lastMonth && item.Name == "Test Name") 
        .OrderByDescending(item=>item.item.CreatedDate) 
        .GroupBy(item=>item.Record) 
        .Select(group => new {Groups = group, Key = group.Key, Count = group.Count()}) 
        .Where(item => item.Groups.Any()); 

從分組數據選擇Form元素

var formElements = groupedData.SelectMany(g => g.Groups).ToList(); 
+0

感謝@RePierre,它像一個魅力一樣工作! – 2012-04-17 16:26:12

0

既然你個人的記錄過濾,您應該分組,而不是前後進行篩選:

(
    from r in db.Form 
    where r.CreatedDate > lastMonth) 
    where r.Name == "Test Name" 
    orderby r.CreatedDate descending 
    group r by r.Record into myGroup 
    where myGroup.Count() > 0 
    select new { Groups = myGroup, myGroup.Key, Count = myGroup.Count() } 
) 
// Groups is a collection of db.Form instances 
+0

疑難雜症,所以我想,片段,現在我得到一個異常。它顯示「select」語句下的錯誤。 無法將類型'System.Linq.IQueryable '隱式轉換爲'System.Collections.Generic.List '。存在明確的轉換(您是否缺少演員?) – 2012-04-13 22:03:36

+1

@JasonFoglia顯示您正在查詢的內容。此外,最好使用'.Any()'而不是'.Count()> 0'。 – phoog 2012-04-13 23:02:47

+0

@JasonFoglia在進一步的思考中,我假設你將查詢的結果分配給一個'List

'。這是行不通的,就像你發現的那樣。試試這個:var list =(從db.Form中的r ...選擇new {...})ToList();' – phoog 2012-04-13 23:10:35