Where clause using a lambda property selector
I want to be able to refresh an object by finding it's match in list of objects that I've got back from the database. I can do it with reflection - but am sure there must be a way of getting the Property Selector within a Where clause.
This is the kind of thing I want to call ...
MyObject = GetRefreshedObject(MyObject, RefreshedObjects, () => ID);
But I'm a bit stuck with the Method!
public static TE GetRefreshed<TE, P>(TE entity, IEnumerable<TE> refreshed, Expression<Func<TE, P>> selector) where TE : class
{
if (e开发者_C百科ntity == null) return null;
return refreshed.Where(x => x.[Selector == entity.Selector]).FirstOfDefault();
//The square bracket bits obviously don't work but hopefully show what I'm trying to achieve!
}
If you are just working with Lambdas and IEnumerables, do you really need the expression parsing? Use the lambda natively. That would require a slight change to your calling code:
var refreshedObject = GetRefreshedObject(MyObject, RefreshedObjects, x => x.ID);
The method implementation would be:
public static TE GetRefreshed<TE, P>(TE entity, IEnumerable<TE> refreshed, Func<TE, P> selector)
{
P myObjectId = selector(entity);
return refreshed.FirstOrDefault(refresh => selector(refresh).Equals(myObjectId));
}
精彩评论