1

Instead of setting each boolean property in object manually. I would like to do it for all boolean properties using reflection.

//For each boolean property: if any in collection is true, result is true.
private ActionFlagsViewModel StackActionFlagsViewModels(List<ActionFlagsViewModel> afList)
{
    var result = new ActionFlagsViewModel();
    foreach (var propInfo in typeof(ActionFlagsViewModel).GetProperties().Where(p => p.PropertyType == typeof(System.Boolean)))
    {
        // TODO: Do this using reflection for each property info.
        result.ShowActionAbort = afList.Where(afvm => afvm.ShowActionAbort == true).Any();
        result.ShowActionAssign = afList.Where(afvm => afvm.ShowActionAssign == true).Any();
    }
    return result;
}

This should be very easy right ?

  • Using reflection when you already know your type seems awfully complicated. Depending on how often your method is run (and how much performance matters to your code), there is also memory and CPU costs. http://stackoverflow.com/questions/224232/what-is-the-cost-of-net-reflection – Chris Tomich Oct 07 '16 at 09:46
  • New actions will likely be added to the model in future changes. And this code is part of presentation logic. I want the code to keep working correctly that means process new flags / booleans that are added. Chances are another programmer, (might even be me in the future) will forget to update this method if not done by reflection. If performance becomes an issue, I will use T4 templates to generate this code. – Tony_KiloPapaMikeGolf Oct 07 '16 at 10:16

2 Answers2

0

This should work (inside the foreach) :

propInfo.SetValue(result, (from m in afList where (bool)propInfo.GetValue(m) select true).FirstOrDefault())
Ben Jackson
  • 1,108
  • 6
  • 9
0


public ActionFlagsViewModel StackActionFlagsViewModels(List<ActionFlagsViewModel> afList)
    {
        var result = new ActionFlagsViewModel();
        foreach (var propInfo in typeof(ActionFlagsViewModel).GetProperties().Where(p => p.PropertyType == typeof(System.Boolean)))
        {
            propInfo.SetValue(result, (from m in afList where (bool)propInfo.GetValue(m) select true).FirstOrDefault());
            //propInfo.SetValue(result, afList.Where(afvm => Convert.ToBoolean(propInfo.GetValue(afvm)) == true).Any());
        }
        return result;
    }

Well this works!

Both statements work. But which one is better ?