2016-07-15 125 views
1

我試圖使用LINQ不是在一個組選擇多列沒有組選擇多列 - C#。我試圖按ISNULL(fieldOne,''),ISNULL(fieldTo,'')分組,然後爲每個組選擇field_One,field_Two,field_Three。因此,對於該組將返回的每一行,我想看到許多行。LINQ GROUP BY和

到目前爲止,我有以下,但似乎無法選擇所有需要的列。

var xy = tableQueryable.Where(
      !string.IsNullOrEmpty(cust.field_One) 
      || ! string.IsNullOrEmpty(ust.field_Two) 
      ).GroupBy(cust=> new { field_One= cust.field_One ?? string.Empty, field_Tow = cust.field_Two ?? string.Empty}).Where(g=>g.Count()>1).AsQueryable(); 

有人可以幫忙嗎?

回答

3

您是非常有 - 你缺少的是從該組的Select

var xy = tableQueryable 
    .Where(!string.IsNullOrEmpty(cust.first_name) || ! string.IsNullOrEmpty(ust.lastName)) 
    .GroupBy(cust=> new { first_name = cust.first_name ?? string.Empty, last_name = cust.last_name ?? string.Empty}) 
    .Where(g=>g.Count()>1) 
    .ToList() // Try to work around the cross-apply issue 
    .SelectMany(g => g.Select(cust => new { 
     Id = cust.Id 
    , cust.FirstName 
    , cust.LastName 
    , cust.RepId 
    })); 

Select從每組做你想要的領域的投影,而SelectMany轉儲所有的結果成單子列表。

+0

這看起來不錯,但我不能運行。我收到以下錯誤。 –

+0

System.NotSupportedException:查詢嘗試通過嵌套查詢調用「CrossApply」,但「CrossApply」沒有相應的鍵。 在System.Data.Entity.Core.Query.PlanCompiler.NestPullup.ApplyOpJoinOp(運運,節點n)... –

+0

@MikeTurner我覺得有一個在LINQ2SQL/EF一個問題,你可能要插入'ToList',說,在第二個「Where」之後,以便在內存中完成分組。請參閱編輯。 – dasblinkenlight

2
請問

這對你的工作?

var groupsWithDuplicates = tableQueryable 
    .Where(c => !string.IsNullOrWhiteSpace(c.first_name) || !string.IsNullOrWhiteSpace(c.last_name)) 
    .GroupBy(c => new { FirstName = c.first_name ?? "", LastName = c.last_name ?? "" }) 
    .Where(group => group.Count() > 1) // Only keep groups with more than one item 
    .ToList(); 

var duplicates = groupsWithDuplicates 
    .SelectMany(g => g) // Flatten out groups into a single collection 
    .Select(c => new { c.first_name, c.last_name, c.customer_rep_id }); 
+0

可惜 - 我得到了同樣的錯誤 - –

+0

System.NotSupportedException:查詢試圖調用「CrossApply」在嵌套查詢,但「CrossApply」沒有合適的鍵。 –

+0

它試圖在SQL中做太多工作。您可以在.ToList()中放入數據,並使用LINQ to Objects完成剩下的工作。看到我上面的編輯。 –