dimanche 30 août 2020

How to test if an object is a string? [duplicate]

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

Aucun commentaire:

Enregistrer un commentaire