简体   繁体   中英

C# using propertyinfo ( reflection ) in LINQ statement

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 ?

这应该工作(在foreach内部):

propInfo.SetValue(result, (from m in afList where (bool)propInfo.GetValue(m) select true).FirstOrDefault())

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 ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM