-1

I have a list of objects that I need to remove all strings from, leaving me with only integers in the list.

The problem I'm having is that some of the strings only contain numbers, for example "1" is a string. If I use is in an if statement if (listOfItems[i] is string) will not work on "1" I've also tried GetType() and typeof as shown below but I'm having the same problem.

How do I test if an object is a string, even if that string contain numbers?

public static class Filter
    {
        public static IEnumerable<int> GetIntegersFromList(List<object> listOfItems)
        {
            for (int i = 0; i < listOfItems.Count; i++)
            {
                if (listOfItems[i].GetType() != typeof(int))
                    listOfItems.RemoveAt(i);
            }
            List<int> listOfInts = new List<int>();
            for (int i = 0; i < listOfItems.Count; i++)
            {
                listOfInts.Add((int)listOfItems[i]);
            }
            return listOfInts;
        }
    }
steve51516
  • 109
  • 4

1 Answers1

4

Disregarding any other problems, you could use OfType to filter all objects that are in fact boxed int

Filters the elements of an IEnumerable based on a specified type.

var ints = listOfItems.OfType<int>().ToList();
TheGeneral
  • 79,002
  • 9
  • 103
  • 141