【问题标题】:Unable to cast object of type 'WhereListIterator`1[System.Object]' to type 'System.Collections.Generic.IEnumerable`1[System.Int32]'无法将“WhereListIterator`1[System.Object]”类型的对象转换为“System.Collections.Generic.IEnumerable`1[System.Int32]”类型
【发布时间】: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&lt;int&gt;(); 老实说,GetIntegersFromList 是不必要的,因为它只是复制了Enumerable.OfType 的行为。
  • @JohnathanBarclay 我返回了它,现在作为输出我得到 'System.Linq.Enumerable+d__95`1[System.Int32]'

标签: c# asp.net .net ienumerable


【解决方案1】:

Linq 的Where() 返回一个WhereListIterator&lt;T&gt;,T 是源T 的IEnumerable&lt;T&gt;,在你的情况下仍然是object。

Cast&lt;T&gt;:

IEnumerable<int> ints = (IEnumerable<int>)listOfItems.Where(x => x is int).Cast<int>();

或者,更短的,使用OfType&lt;T&gt;():

IEnumerable<int> ints = listOfItems.OfType<int>();

【讨论】:

  • 我得到 'System.Collections.Generic.List`1[System.Int32]' 作为输出
  • 是的,那是因为您将类型名称写入控制台。您需要打印集合的内容,例如Console.WriteLine(string.Join(", ", GetIntegersFromList(list))。
【解决方案2】:

如果您尝试将整数写入控制台,则需要将 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;
    }
}

【讨论】:

  • 我需要写出函数 public static IEnumerable GetIntegersFromList(List listOfItems)
  • @Dragana 为什么?这就是OfType 所做的。
  • 可能是家庭作业,他们必须提供该方法的实现。很可能在这种情况下,也不允许使用 Linq。
  • 任务如下:'创建一个函数,该函数接受一个非负整数和字符串列表,并返回一个过滤掉字符串的新列表。我被赋予了我应该编写代码的空白函数
  • 我认为 linq 是允许的,因为它在过去的任务中有点需要
猜你喜欢
  • 2015-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-22
  • 1970-01-01
  • 2023-04-03
  • 2013-10-06
  • 2014-01-29
相关资源
最近更新 更多