Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, get all collection properties from an object

I have a class with 3 List collections like the following.

I am trying to have a logic which will iterate through the object's "collection" properties and do some operation using the data stored in those collections.

I am just wondering if there is an easy way of doing it using foreach. thanks

public class SampleChartData
    {
        public List<Point> Series1 { get; set; }
        public List<Point> Series2 { get; set; }
        public List<Point> Series3 { get; set; }

        public SampleChartData()
        {
            Series1 = new List<Point>();
            Series2 = new List<Point>();
            Series3 = new List<Point>();
        }
    }
like image 689
Eatdoku Avatar asked Jun 11 '10 16:06

Eatdoku


2 Answers

Function to get all IEnumerable<T> from object:

public static IEnumerable<IEnumerable<T>> GetCollections<T>(object obj)
{
    if(obj == null) throw new ArgumentNullException("obj");
    var type = obj.GetType();
    var res = new List<IEnumerable<T>>();
    foreach(var prop in type.GetProperties())
    {
        // is IEnumerable<T>?
        if(typeof(IEnumerable<T>).IsAssignableFrom(prop.PropertyType))
        {
            var get = prop.GetGetMethod();
            if(!get.IsStatic && get.GetParameters().Length == 0) // skip indexed & static
            {
                var collection = (IEnumerable<T>)get.Invoke(obj, null);
                if(collection != null) res.Add(collection);
            }
        }
    }
    return res;
}

Then you can use something like

var data = new SampleChartData();
foreach(var collection in GetCollections<Point>(data))
{
    foreach(var point in collection)
    {
        // do work
    }
}

to iterate through all elements.

like image 88
max Avatar answered Oct 03 '22 16:10

max


Use Reflection to get the objects Properties. Then iterate over those to see is IEnumerable<T>. Then iterate over the IEnumerable properties

like image 20
Greg B Avatar answered Oct 03 '22 14:10

Greg B