How to get the items count from an IList<> got as an object?

29.8k Views Asked by At

In a method, I get an object.

In some situation, this object can be an IList of "something" (I have no control over this "something").

I am trying to:

  1. Identify that this object is an IList (of something)
  2. Cast the object into an "IList<something>" to be able to get the Count from it.

For now, I am stuck and looking for ideas.

4

There are 4 best solutions below

1
On BEST ANSWER

You can check if your object implements IList using is.

Then you can cast your object to IList to get the count.

object myObject = new List<string>();

// check if myObject implements IList
if (myObject  is IList)
{
   int listCount = ((IList)myObject).Count;
}
8
On
if (obj is ICollection)
{
    var count = ((ICollection)obj).Count;
}
0
On
        object o = new int[] { 1, 2, 3 };

        //...

        if (o is IList)
        {
            IList l = o as IList;
            Console.WriteLine(l.Count);
        }

This prints 3, because int[] is a IList.

2
On

Since all you want is the count, you can use the fact that anything that implements IList<T> also implements IEnumerable; and furthermore there is an extension method in System.Linq.Enumerable that returns the count of any (generic) sequence:

var ienumerable = inputObject as IEnumerable;
if (ienumerable != null)
{
    var count = ienumerable.Cast<object>().Count();
}

The call to Cast is because out of the box there isn't a Count on non-generic IEnumerable.