![](/img/trans.png)
[英]Unable cast <TakeIterator>d__3a`1[System.Object] to type System.Collections.Generic.IEnumerable
[英]Unable to cast object of type 'WhereListIterator`1[System.Object]' to type 'System.Collections.Generic.IEnumerable`1[System.Int32]'
我正在尝试编写函数以从对象列表中返回所有整数,但我不断收到:“无法将类型为“WhereListIterator 1[System.Object]' to type 'System.Collections.Generic.IEnumerable
对象转换为“System.Collections.Generic.IEnumerable 1[System.Object]' to type 'System.Collections.Generic.IEnumerable
。 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() 并且我总是得到无效的投射异常。
输出应该是:{1, 2}
LINQ的Where()
返回一个WhereListIterator<T>
与T
作为T
源IEnumerable<T>
你的情况仍然object
。
要么Cast<T>
:
IEnumerable<int> ints = (IEnumerable<int>)listOfItems.Where(x => x is int).Cast<int>();
或者,更短的,使用OfType<T>()
:
IEnumerable<int> ints = listOfItems.OfType<int>();
如果您尝试将整数写入控制台,则需要将IEnumerable
转换为string
:
var list = new List<object>() { 1, 2, "a", "b" };
Console.WriteLine(string.Join(", ", list.OfType<int>()));
// Output: 1, 2
或者迭代IEnumerable
:
var list = new List<object>() { 1, 2, "a", "b" };
foreach (int i in list.OfType<int>()) Console.WriteLine(i);
// Output:
// 1
// 2
如果您必须实现GetIntegersFromList
那么您可以创建一个简单的传递:
public static IEnumerable<int> GetIntegersFromList(List<object> listOfItems)
=> listOfItems.OfType<int>();
或者,如果您不能使用 LINQ:
public static IEnumerable<int> GetIntegersFromList(List<object> listOfItems)
{
foreach (var item in listOfItems)
{
if (item is int i) yield return i;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.