如何将List转换为IEnumerable?

Yar*_*zov 0 c# ienumerable list

我正在解决一个需要编写一个函数的问题,该函数只返回一个对象List中的整数(我编写了函数但它不起作用).我已经想了很长时间如何将List转换为IEnumerable,我正在寻找如何解决问题,但我还没有找到合适的解决方案.拜托,任何人都可以帮我解决这个问题吗?

public static IEnumerable<int> GetIntegersFromList(List<object> listOfItems)
{
    List<object> result = new List<object>();
    for (int i = 0; i < listOfItems.Count - 1; i++)
    {
        if (listOfItems[i] is string)//the input is only integers and strings
        {
            listOfItems.RemoveAt(i);
        }
    }
    return listOfItems;//this doesn't work
}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 10

您没有将列表转换为IEnumeruble<T>- 列表已经是IEnumerable<T>.在你的代码的问题是,名单objects是不是一个IEnumerable<int>.

你有三种解决方法:

  • 制作一个新的List<int>,在你的循环中填充它,然后返回它,或者
  • 使用yield return以避免明确构建列表,或者
  • 应用LINQ OfType<int>listOfItems将结果放在一行代码中.