我希望能够通过在数据库中找回的对象列表中找到它来匹配对象。我可以用反射来做 - 但是我确定必须有一种方法可以将属性选择器放在Where子句中。
这是我想要称之为......
MyObject = GetRefreshedObject(MyObject, RefreshedObjects, () => ID);
但是我对方法有点困惑了!
public static TE GetRefreshed<TE, P>(TE entity, IEnumerable<TE> refreshed, Expression<Func<TE, P>> selector) where TE : class
{
if (entity == 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!
}
答案 0 :(得分:3)
如果你只是使用Lambdas和IEnumerables,你真的需要表达式解析吗?本机使用lambda。这需要对您的调用代码稍作更改:
var refreshedObject = GetRefreshedObject(MyObject, RefreshedObjects, x => x.ID);
方法实现将是:
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));
}