无法将类型 'WhereListIterator`1[System.Object]' 的对象转换为类型 'System.Collections.Generic.IEnumerable`1[System.Int32]'

Unable to cast object of type 'WhereListIterator`1[System.Object]' to type 'System.Collections.Generic.IEnumerable`1[System.Int32]'

我正在尝试编写函数以从对象列表中获取 return 所有整数,但我不断收到:“无法转换 '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() 并且我总是得到无效转换异常。

输出应该是:{1, 2}

Linq 的 Where() returns a WhereListIterator<T>,其中 T 是来源 IEnumerable<T>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;
    }
}