Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the Count of a List of unknown type

I am calling a function that returns an object and in certain circumstances this object will be a List.

A GetType on this object might gives me:

{System.Collections.Generic.List`1[Class1]}

or

{System.Collections.Generic.List`1[Class2]}

etc

I don't care what this type is, all I want is a Count.

I've tried:

Object[] methodArgs=null;
var method = typeof(Enumerable).GetMethod("Count");
int count = (int)method.Invoke(list, methodArgs);

but this gives me an AmbiguousMatchException which I can't seem to get around without knowing the type.

I've tried casting to IList but I get:

Unable to cast object of type 'System.Collections.Generic.List'1[ClassN]' to type 'System.Collections.Generic.IList'1[System.Object]'.

UPDATE

Marcs answer below is actually correct. The reason it wasn't working for me is that I have:

using System.Collections.Generic;

at the top of my file. This means I was always using the Generic versions of IList and ICollection. If I specify System.Collections.IList then this works ok.

like image 400
Chris Simpson Avatar asked Aug 05 '10 18:08

Chris Simpson


2 Answers

Cast it to ICollection and use that .Count

using System.Collections;

List<int> list = new List<int>(Enumerable.Range(0, 100));

ICollection collection = list as ICollection;
if(collection != null)
{
  Console.WriteLine(collection.Count);
}
like image 199
Marc Avatar answered Nov 11 '22 19:11

Marc


You could do this

var property = typeof(ICollection).GetProperty("Count");
int count = (int)property.GetValue(list, null);

assuming you want to do this via reflection that is.

like image 3
Brian Rasmussen Avatar answered Nov 11 '22 20:11

Brian Rasmussen