首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >不能将类型'System.Collections.Generic.List<object>‘隐式转换为'System.Collections.Generic.IEnumerable<int>

不能将类型'System.Collections.Generic.List<object>‘隐式转换为'System.Collections.Generic.IEnumerable<int>
EN

Stack Overflow用户
提问于 2021-10-10 01:49:42
回答 2查看 615关注 0票数 0

我想构建一个函数,它接受非负整数和字符串的列表,并返回一个过滤掉字符串的新列表。

如下所示:

代码语言:javascript
运行
复制
ListFilterer.GetIntegersFromList(new List<object>(){1, 2, "a", "b"}) => {1, 2}
ListFilterer.GetIntegersFromList(new List<object>(){1, 2, "a", "b", 0, 15}) => {1, 2, 0, 15}

为了做到这一点,我做了以下操作:(通过评论显示的原始尝试)

代码语言:javascript
运行
复制
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class ListFilterer
{
   public static IEnumerable<int> GetIntegersFromList(List<object> listOfItems)
   {
     foreach (var item in listOfItems)
     {
       if(item is string)
       {
         listOfItems.Remove(item);
       }
     }
     // return listOfItems; <- Original attempt
     return listOfItems.ToList(); 

   }
}

这给出了标题中的错误:

代码语言:javascript
运行
复制
src/Solution.cs(16,13): error CS0266: Cannot implicitly convert type 'System.Collections.Generic.List<object>' to 'System.Collections.Generic.IEnumerable<int>'. An explicit conversion exists (are you missing a cast?)

所以我添加了我认为是正确的转换.ToList(),但它最终什么也没做,仍然提供了相同的错误。我被这个问题难住了,因为在搜索和查看了我认为类似的问题之后,我仍然没有找到一个合适的方法来转换它,而且由于我缺乏使用Linq和Enumerable的经验,我不知道去哪里找。

如有任何帮助,我将不胜感激,感谢您抽出时间

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-10-10 02:08:36

错误是因为您已经从列表中删除了所有字符串,但是列表的数据类型仍然是object。您的List<object>仍然可以在其中添加其他数据类型的值,即使您已经删除了其中的所有字符串。简而言之,即使您删除了字符串,但list的底层数据类型仍然是object。在C#中,object是基类,object可以有int,但其他方式是不可能的。这就是为什么c#会给你这个错误。

我的解决方案是:

代码语言:javascript
运行
复制
 //Assuming listOfItems only contains strings and ints. 
 //If other datatypes are there then you have to do int.tryparse to check 
 //whether the current list item can be converted to int and then add that to nums.
 public static IEnumerable<int> GetIntegersFromList(List<object> listOfItems)
 {
     List<int> nums = new List<int>();
     foreach (var item in listOfItems)
     {
        if (!(item is string))
        {
           nums.Add(Convert.ToInt32(item));
        }
     }
     // return listOfItems; <- Original attempt
     return nums;

 }
票数 2
EN

Stack Overflow用户

发布于 2021-10-10 02:05:24

您是否正在寻找:

代码语言:javascript
运行
复制
public static IEnumerable<int> GetIntegersFromList(IEnumerable<object> src) =>
    src.OfType<int>();
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69511733

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档