【发布时间】:2021-01-29 19:00:43
【问题描述】:
我正在尝试编写函数以从对象列表中返回所有整数,但我不断收到:'Unable to cast object of type 'WhereListIterator1[System.Object]' to type 'System.Collections.Generic.IEnumerable1[System.Int32]'。'
static void Main(string[] args)
{
var list = new List<object>() { 1, 2, "a", "b" };
Console.WriteLine(GetIntegersFromList(list));
}
public static IEnumerable<int> GetIntegersFromList(List<object> listOfItems)
{
IEnumerable<int> ints = (IEnumerable<int>) listOfItems.Where(x => x is int);
return ints.ToList();
}
我尝试投射它,而不是投射它,在任何地方添加 ToList(),但我总是得到 Invalid Cast Exception。
输出应该是:{1, 2}
【问题讨论】:
-
ints = listOfItems.OfType<int>();老实说,GetIntegersFromList是不必要的,因为它只是复制了Enumerable.OfType的行为。 -
@JohnathanBarclay 我返回了它,现在作为输出我得到 'System.Linq.Enumerable+
d__95`1[System.Int32]'
标签: c# asp.net .net ienumerable