user3140169
user3140169

Reputation: 221

c# Reflection Generic List Count

Is there a cleaner way to get a list count using reflection then this?

 Boolean include = false;

 foreach (PropertyInfo item in props)
        {
            var pt = item.PropertyType;                

            String listType = pt.GetGenericArguments()[0].Name;

             // Is there a better solution than this?
             switch (listType)
                            {
                                case "jsonResult":
                                    var list = v as List<jsonResult>;

                                    include =  list.count > 0;
                                    break;                                
                            }
        }
    )

I've tried a variety of ideas from Googling but haven't had any luck.

Upvotes: 0

Views: 1060

Answers (1)

Alexandre Ribeiro
Alexandre Ribeiro

Reputation: 193

I didn't completely understand what is the "v" variable, but if it is an object and when it's a collection you want to get its count, you can do that this way:

var count = GetCount(v);

if (!count.HasValue)
    continue; // Or any other code here
    
include =  count.Value > 0;

The "GetCount" method:

private static int? GetCount(object @object)
{
    var collection = @object as System.Collections.ICollection;
    if (collection == null)
        return null;
    
    return collection.Count;
}

Upvotes: 1

Related Questions