Home > OS >  Cannot implicitly convert type 'System.Collections.Generic.List<object>' to 'Sy
Cannot implicitly convert type 'System.Collections.Generic.List<object>' to 'Sy

Time:10-10

I want to build a function that takes a list of non-negative integers and strings and returns a new list with the strings filtered out.

Similar to this:

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}

To do this I did the following: (With the original attempt shown by the comment)

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(); 

   }
}

This gave the error in the title:

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?)

So i added what I thought would be the right conversion .ToList() but it ended up not doing anything and still provided the same error. I am stumped on this because after searching and looking at what I thought were similar questions I still haven't found a proper way to convert it and due to my inexperience with Linq and Enumerable stuff I'm not sure where to look.

Any help would be appreciated, thank you for your time

CodePudding user response:

Are you perhaps looking for:

public static IEnumerable<int> GetIntegersFromList(IEnumerable<object> src) =>
    src.OfType<int>();

CodePudding user response:

The error is because you have removed all the strings from your list, but the data type of your list is still object. Your List<object> can still add values of other datatypes in it even if you have removed all your strings from it. In short, even you have removed the strings but the underlying datatype of list is still object. In C#, object is the base class and object can have ints but other way around is not possible. That's why c# is giving you this error.

My solution would be:

 //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;

 }
  • Related