Reputation: 6961
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>();
}
}
Upvotes: 5
Views: 24005
Reputation: 6961
Just found a quick solution, but maybe some of you have better ways of doing it. this is what I did.
SampleChartData myData = DataFeed.GetData();
Type sourceType = typeof(SampleChartData);
foreach (PropertyInfo pi in (sourceType.GetProperties()))
{
if (pi.GetValue(myData, null).GetType() == typeof(List<Point>))
{
List<Point> currentSeriesData = (List<Point>)pi.GetValue(myData, null);
// then do something with the data
}
}
Upvotes: 0
Reputation: 3156
You can use reflection to get the list of properties from the object. This example gets all the properties and prints their name and Count to the console:
public static void PrintSeriesList()
{
SampleChartData myList = new SampleChartData();
PropertyInfo[] Fields = myList.GetType().GetProperties();
foreach(PropertyInfo field in Fields)
{
var currentField = field.GetValue(myList, null);
if (currentField.GetType() == typeof(List<Point>))
{
Console.WriteLine("List {0} count {1}", field.Name, ((List<Point>)currentField).Count);
}
}
}
Upvotes: 0
Reputation: 34427
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.
Upvotes: 13
Reputation: 14898
Use Reflection to get the objects Properties. Then iterate over those to see is IEnumerable<T>
. Then iterate over the IEnumerable properties
Upvotes: 2