對不起,打開另一篇文章。SelectMany c#linq
我問在以前的帖子,但我不能讓我的問題的解決方案。
`
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 })
但它是不正確的......
預先感謝您
勞爾
使用'new'而不是'new []' –
這裏不需要'SelectMany'。它用於將序列拼合成一個序列。停止對象中沒有任何序列。還排在第一位的月份看起來很奇怪 –
可能與[.SelectMany與C#]重複(https://stackoverflow.com/questions/43112943/selectmany-with-c-sharp)....不要問重複的問題,尤其是當第一個已經有答案了 – EpicKip