lundi 25 novembre 2019

Reflection with LINQ without for or foreach

I'm trying to filter a list of objects based on specific properties via reflection. The problem is I can't find a way to do it without a for or foreach loop. Not that there's anything wrong with that, but I'd like to use LINQ to capture the object I'm filtering for instead.

string prop = 'SortOrder';
string propVal = '1';
PropertyInfo result;
//StackObject is passed in and can contain over a million objects
var objList = (StackObject as IEnumerable).Cast<object>().ToList();

foreach (var obj in objList)
{
    PropertyInfo filterProperty = obj.GetType().GetProperty(prop);

    if (filterProperty.GetValue(obj, null).ToString() == propVal)
    {
        result = (PropertyInfo)obj;
        return result;
    }
}

I have tried this:

var objList = (StackObject as IEnumerable).Cast<object>().ToList();
PropertyInfo desiredObject = (PropertyInfo)objList.Where(o => o.GetType().GetProperty(prop).GetValue(o, null).ToString() == propVal);

But I keep getting a list of objects or null instead of the specific object. The end goal is to be more performant (as the list of objects can grow quite large at times) and filter appropriately for a given property.





Aucun commentaire:

Enregistrer un commentaire