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:
IList
(of something)object
into an "IList<something>
" to be able to get the Count
from it.For now, I am stuck and looking for ideas.
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#.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With