You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#过滤列表字符串时报错无法将List<object>转换为IEnumerable<int>如何解决

问题根因
  • 类型不匹配:你返回的List<object>和方法声明的返回值IEnumerable<int>类型不兼容,ToList()仅用于转换集合容器类型,不会自动对集合内的元素做类型转换。
  • 隐藏逻辑错误:在foreach遍历原集合的同时调用Remove删除元素,会触发InvalidOperationException异常,因为C#不允许在foreach迭代过程中修改原集合的结构。同时修改传入的参数列表也会产生额外副作用,不符合「返回新列表」的需求。
解决方案

方案1:使用Linq简洁实现

直接调用Linq提供的OfType<T>()方法,自动筛选出集合中类型为int的元素,完美匹配返回值要求:

using System.Collections.Generic;
using System.Linq;

public class ListFilterer
{
   public static IEnumerable<int> GetIntegersFromList(List<object> listOfItems)
   {
       return listOfItems.OfType<int>().ToList();
   }
}

OfType<int>会遍历所有元素,仅保留类型为int的元素,同时直接返回IEnumerable<int>类型,不需要额外转换,也不会修改原输入列表。

方案2:不使用Linq的原生实现

如果不想依赖Linq,可以新建一个int类型的列表存储结果,遍历原列表筛选符合要求的元素即可:

using System.Collections.Generic;

public class ListFilterer
{
   public static IEnumerable<int> GetIntegersFromList(List<object> listOfItems)
   {
       List<int> result = new List<int>();
       foreach (var item in listOfItems)
       {
           if (item is int intValue)
           {
               result.Add(intValue);
           }
       }
       return result;
   }
}

内容的提问来源于stack exchange,提问作者Muffin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 16:54:07