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>();
}
}
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.
Use Reflection to get the objects Properties. Then iterate over those to see is IEnumerable<T>
. Then iterate over the IEnumerable properties
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