簡體   English   中英

從System.Collections.Generic.IEnumerable中獲取前n個元素

[英]Take first n elements from System.Collections.Generic.IEnumerable

從數據庫中,我得到的結果為System.Collections.Generic.IEnumerable<CustomObject> 將結果放入List<CustomObject>可以正常工作。 現在,我只想獲取前n個對象。 這是我嘗試過的:

List<CustomObject> tempList = DataBase.GetAllEntries().Cast<CustomObject>().ToList();
tempList = tempList.Take(5);

在第二行,我得到

Error   CS0266  Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<CustomObject>' to 'System.Collections.Generic.List<CustomObject>'. An explicit conversion exists (are you missing a cast?)

我還嘗試添加OrderBy() ,僅使用ToList() (不強制轉換)或其組合,但是每次遇到上述錯誤時,我都會嘗試添加。 我應該改變什么?

Take放在實現之前ToList ):

List<CustomObject> tempList = DataBase.GetAllEntries()
  .Take(5)
  .Cast<CustomObject>()
  .ToList();

讓物化是最后的操作。

您的問題是tempListList<CustomObject> ,但是List<CustomObject> .Take()返回IEnumerable<CustomObject> 您可以通過再次調用.ToList()來解決此問題:

tempList = tempList.Take(5).ToList();

或者,您可以在原始查詢中添加.Take()方法,以避免構建2個列表:

List<CustomObject> tempList = DataBase.GetAllEntries().Take(5).Cast<CustomObject>().ToList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM