Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 819
remio Avatar asked Jan 25 '12 09:01

remio


People also ask

How to check number of items in list C#?

Alternatively, to get the count of a single element, filter the list using the Where() method to obtain matching values with the specified target, and then get its count by invoking the Count() method. That's all about getting the count of the number of items in a list in C#.

What is IList type in C#?

In C# IList interface is an interface that belongs to the collection module where we can access each element by index. Or we can say that it is a collection of objects that are used to access each element individually with the help of an index. It is of both generic and non-generic types.

How to define IList?

List and IList are used to denote a set of objects. They can store objects of integers, strings, etc. There are methods to insert, remove elements, search and sort elements of a List or IList. The major difference between List and IList is that List is a concrete class and IList is an interface.


1 Answers

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;
}
like image 116
dknaack Avatar answered Oct 25 '22 23:10

dknaack