2017-06-15 106 views
-3

對不起,打開另一篇文章。SelectMany c#linq

.SelectMany with C#

我問在以前的帖子,但我不能讓我的問題的解決方案。

`

var departments = stops 
    .Where(stop => stop.InitDate != null) 
    .SelectMany(stop => new[] { Month = stop.InitDate.Month, Year = stop.InitDate.Year, Duration = stop.Duration }) 
    .GroupBy(dt => new { dt.Month, dt.Year }) 
    .OrderBy(g => g.Key.Month) 
    .ThenBy(g => g.Key.Year) 
    .Select(g => new 
    { 
     Key = g.Key.Month, 
     Año = g.Key.Year, 
     Duration = g.Sum(v => v.Duration), 
     Count = g.Count() 
    }); 

`

這是德最終解決我的問題,但是,當我用這個在我的代碼,我有一些問題。

如果我不聲明變量「月,年,持續時間」,我得到一個錯誤: .SelectMany(stop => new[] { Month = stop.InitDate.Month, Year = stop.InitDate.Year, Duration = stop.Duration })

但我不知道他們是什麼樣的數據年份和月份,因爲如果我聲明它是如何整數,我得到一個錯誤.GroupBy(dt => new { dt.Month, dt.Year }),因爲編譯器將dt識別爲整數。

我想聲明月份和年份爲整數,並把在.GroupBy這樣的: .GroupBy(dt => new { Month, Year })但它是不正確的......

預先感謝您

勞爾

+4

使用'new'而不是'new []' –

+3

這裏不需要'SelectMany'。它用於將序列拼合成一個序列。停止對象中沒有任何序列。還排在第一位的月份看起來很奇怪 –

+2

可能與[.SelectMany與C#]重複(https://stackoverflow.com/questions/43112943/selectmany-with-c-sharp)....不要問重複的問題,尤其是當第一個已經有答案了 – EpicKip

回答

0

顯然你有一個名爲Stops的序列,它是stop對象的序列。每個stop對象可能或可能沒有InitDate。如果它有一個InitDate,這個InitDate至少有屬性Month,YearDuration,這些都是int

你想要的是從你的原始Stops,只有那些stop對象有一個InitDate。從您選擇的每個stop對象中,想要創建一個新對象,其中Key屬性包含Month和Year以及包含Duration的Duration屬性。

你幾乎在那裏。您的問題是您使用SelectMany而不是簡單的Select

通常情況下,如果您想要連接成一個序列的序列序列,則使用SelectMany。但是您的Stops沒有序列。每個stop對象應產生一個「具有年份,月份和持續時間的新對象」。

或者用簡單的話:只要你有「一樣的東西」的集合,你想每一個「啄」轉換成只有一個「其他啄」,你應該使用Select,不SelectMany

你的情況選擇將是:

var stopData = stops 
    .Where(stop => stop.InitDate != null) 
    .Select(stop => new 
    { 
     GroupKey = new 
     { 
      Month = stop.InitDate.Month, 
      Year = stop.InitDate.Year, 
     }, 
     Duration = stop.Duration 
    }); 

我把年份和月份alreay在屬性GroupKey,因爲這使得分組更容易:

var groupsOfSameMonth = stopData 
    .GroupBy(item => item.Key, item => item.Duration); 

現在每個組都包含一個密鑰,即{Month,Year}。該組的元素都是這個{month,year}的持續時間。所以,現在你需要做的就是從每一個組,採取從組和總和(所有元素)和計數()他們:

var durationsOfSameMonth = groupsOfSameMonth 
    .Select(group => new 
    { 
     Month = group.Key.Month, // I assumed your Key was an error 
     Año = group.Key.Year, 
     Duration = group.Sum(), 
     Count = group.Count() 
    }); 

所有你需要做的是一些排序,你就完成了。

+0

你的意思是在你的第一個片段中使用'SelectMany'嗎? –

+0

哎呀,我的錯。更正 –

+0

非常感謝,我的代碼正常工作 –