我想构建一个函数,它接受非负整数和字符串的列表,并返回一个过滤掉字符串的新列表。
如下所示:
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}
为了做到这一点,我做了以下操作:(通过评论显示的原始尝试)
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();
}
}
这给出了标题中的错误:
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的经验,我不知道去哪里找。
如有任何帮助,我将不胜感激,感谢您抽出时间
发布于 2021-10-10 02:08:36
错误是因为您已经从列表中删除了所有字符串,但是列表的数据类型仍然是object。您的List<object>
仍然可以在其中添加其他数据类型的值,即使您已经删除了其中的所有字符串。简而言之,即使您删除了字符串,但list的底层数据类型仍然是object。在C#中,object是基类,object可以有int,但其他方式是不可能的。这就是为什么c#会给你这个错误。
我的解决方案是:
//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;
}
发布于 2021-10-10 02:05:24
您是否正在寻找:
public static IEnumerable<int> GetIntegersFromList(IEnumerable<object> src) =>
src.OfType<int>();
https://stackoverflow.com/questions/69511733
复制相似问题