[英]Unable to cast object of type 'WhereListIterator`1[System.Object]' to type 'System.Collections.Generic.IEnumerable`1[System.Int32]'
I'm trying to write function to get return all integers from object list and I keep getting: '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();
}
I tried casting it, not casting it, adding ToList() everywhere and I always get the Invalid Cast Exception.我尝试投射它,而不是投射它,到处添加 ToList() 并且我总是得到无效的投射异常。
The output should be: {1, 2}输出应该是:{1, 2}
Linq's Where()
returns a WhereListIterator<T>
, with T
being the T
of the source IEnumerable<T>
, in your case still object
. LINQ的
Where()
返回一个WhereListIterator<T>
与T
作为T
源IEnumerable<T>
你的情况仍然object
。
Either Cast<T>
:要么
Cast<T>
:
IEnumerable<int> ints = (IEnumerable<int>)listOfItems.Where(x => x is int).Cast<int>();
Or, shorter, use OfType<T>()
:或者,更短的,使用
OfType<T>()
:
IEnumerable<int> ints = listOfItems.OfType<int>();
If you're trying to write the integers to the console, you will need to convert the IEnumerable
to a string
:如果您尝试将整数写入控制台,则需要将
IEnumerable
转换为string
:
var list = new List<object>() { 1, 2, "a", "b" };
Console.WriteLine(string.Join(", ", list.OfType<int>()));
// Output: 1, 2
Or iterate over the IEnumerable
:或者迭代
IEnumerable
:
var list = new List<object>() { 1, 2, "a", "b" };
foreach (int i in list.OfType<int>()) Console.WriteLine(i);
// Output:
// 1
// 2
If you must implement GetIntegersFromList
then you can just create a simple pass through:如果您必须实现
GetIntegersFromList
那么您可以创建一个简单的传递:
public static IEnumerable<int> GetIntegersFromList(List<object> listOfItems)
=> listOfItems.OfType<int>();
Or if you cannot use LINQ:或者,如果您不能使用 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.