从 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()
(不强制转换)或其组合,但每次我都会收到上述错误。我应该改变什么?
您的问题是 tempList
是 List<CustomObject>
,而 .Take()
returns 是 IEnumerable<CustomObject>
。您只需再次调用 .ToList()
即可修复它:
tempList = tempList.Take(5).ToList();
或者,您可以在原始查询中添加 .Take()
方法以避免构建 2 个列表:
List<CustomObject> tempList = DataBase.GetAllEntries().Take(5).Cast<CustomObject>().ToList();
将Take
放在实现之前(ToList
):
List<CustomObject> tempList = DataBase.GetAllEntries()
.Take(5)
.Cast<CustomObject>()
.ToList();
让具体化成为最终操作。
从数据库中我得到的结果是 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()
(不强制转换)或其组合,但每次我都会收到上述错误。我应该改变什么?
您的问题是 tempList
是 List<CustomObject>
,而 .Take()
returns 是 IEnumerable<CustomObject>
。您只需再次调用 .ToList()
即可修复它:
tempList = tempList.Take(5).ToList();
或者,您可以在原始查询中添加 .Take()
方法以避免构建 2 个列表:
List<CustomObject> tempList = DataBase.GetAllEntries().Take(5).Cast<CustomObject>().ToList();
将Take
放在实现之前(ToList
):
List<CustomObject> tempList = DataBase.GetAllEntries()
.Take(5)
.Cast<CustomObject>()
.ToList();
让具体化成为最终操作。