2015-10-01 81 views
0

我想訂購一些用戶發佈帖子的次數。通過分組數量訂購物品

我有以下幾點:

IList<User> orderTopContributors = 
    this.GetPosts() 
    .GroupBy(x => x.Author.Id) 
    .Select(x => new 
    { 
     AuthorCount = x.Count() 
    }) 
    .OrderByDescending(x => x.AuthorCount) 
    .ToList(); 

我在哪裏去了?沒有與鑄造一個錯誤:

嚴重性代碼說明項目文件行錯誤CS0266不能 隱式轉換類型「System.Collections.Generic.List <用品>>」到 「System.Collections.Generic.IList 」。一個顯式轉換 存在(是否缺少強制轉換?)

+2

'OrderByDescending'' –

+0

感謝您注意到嘿嘿。 – Jimmyt1988

+0

當你應用'Select'子句時,你得到一個'IEnumerable'對象,其元素是'Select'中定義的新類型,所以,當你在'Select'子句中放入'new'時,它會返回一個新類型的IEnumerable列表。 – mggSoft

回答

1

TL;博士:使用SelectMany方法

你有幾個錯誤:

  • 首先, (您在編輯中修復了此問題),您應該使用OrderByDescending爲了獲得從最大到最小的訂單。

  • 下一頁(你解決了這個問題一個在編輯),你期望接收IList<User>,要麼將其更改爲IEnumrable<User>或在您的LINQ的末尾添加.ToList()

  • 最後,如果你想彙整組到一個列表中使用SelectMany並選擇您的扁平列表

示例代碼:

IList<User> orderTopContributors = GetPosts() 
    .GroupBy(x => x.Id) 
    .Select(x => new 
    { 
     AuthorCount = x.Count(), 
     Posts = x 
    }) 
    .OrderByDescending(x => x.AuthorCount) 
    .SelectMany(x => x.Posts) 
    .ToList(); 

當您使用.GroupBy你把你的IEnumerable<User>變成IEnumerable<IEnumerable<User>>因爲有幾組(很多很多),通過使用要從各組取和它聚集到最終結果是IEnumerable<T>SelectMany方法你陳述:

實施例的僞:

var Users = new List<User> 
{ 
    { UserID = 576, PostId = 7 }, 
    { UserID = 576, PostId = 4 }, 
    { UserID = 4, PostId = 2 }, 
    { UserID = 2, PostId = 5 }, 
    { UserID = 2, PostId = 1 }, 
    { UserID = 576, PostId = 9 } 
} 

var Ordered = Users 
    .GroupBy(x => x.UserID) 
    .Select(x => new 
    { 
     AuthorCount = x.Count(), 
     Posts = x 
    }) 
    .OrderByDescending(x => x.AuthorCount) 
    .SelectMany(x => x.Posts) 
    .ToList(); 

Ordered現在爲:

List<User> 
{ 
    { UserID = 576, PostId = 7 }, 
    { UserID = 576, PostId = 4 }, 
    { UserID = 576, PostId = 9 }, 
    { UserID = 2, PostId = 5 }, 
    { UserID = 2, PostId = 1 }, 
    { UserID = 4, PostId = 2 } 
} 
+0

我修改了一下我的問題,不知道它是如何令人困惑 – Jimmyt1988

+0

閱讀我寫的關於'.SelectMany()' –

+0

謝謝,我會改變你的代碼到解決方案,我還是一個noob以及 – Jimmyt1988