How to filter List<T> with LINQ and Reflection
- by Ehsan Sajjad
i am getting properties via reflection and i was doing like this to iterate on the list.
private void HandleListProperty(object oldObject, object newObject, string difference, PropertyInfo prop)
{
var oldList = prop.GetValue(oldObject, null) as IList;
var newList = prop.GetValue(newObject, null) as IList;
if (prop.PropertyType == typeof(List<DataModel.ScheduleDetail>))
{
List<DataModel.ScheduleDetail> ScheduleDetailsOld = oldList as List<DataModel.ScheduleDetail>;
List<DataModel.ScheduleDetail> ScheduleDetailsNew = newList as List<DataModel.ScheduleDetail>;
var groupOldSchedules = ScheduleDetailsOld
.GroupBy(x => x.HomeHelpID)
.SelectMany(s => s.DistinctBy(d => d.HomeHelpID)
.Select(h => new { h.HomeHelpID, h.HomeHelpName }));
}
}
Now i am making it generic because there will be coming different types of Lists and i don't want to put if conditions this way i want to write
generic code to handle any type of list.
I came up with this way:
private void HandleListProperty(object oldObject, object newObject, string difference, PropertyInfo prop)
{
var oldList = prop.GetValue(oldObject, null) as IList;
var newList = prop.GetValue(newObject, null) as IList;
var ListType = prop.PropertyType;
var MyListInstance = Activator.CreateInstance(ListType);
MyListInstance = oldList;
}
i am able to get the items in MyListInstance but as the type will come at runtime i am not getting how to write linq query to filter them, any ideah how to do.