lambda到表达式树

时间:2012-04-05 23:38:38

标签: c# expression-trees

如何将以下lambda转换为表达式树?

source.Join(lookup, s => s.Id, l => l.Id, (s,l) => l)

我认为除了resultSelector(s,l)=>之外我已经涵盖了所有内容。升。

这是我的代码..谢谢!

public static IQueryable<TLookup> GetLookupSource<T, TLookup, TKey>(this IQueryable<T> source, IQueryable<TLookup> lookup{
   ParameterExpression s = Expression.Parameter(source.ElementType, "s");
   Expression<Func<T, TKey>> outerKeySelector = Expression.Lambda<Func<T, TKey>>(Expression.PropertyOrField(s, "Id"), s);

   ParameterExpression l = Expression.Parameter(lookup.ElementType, "l");
   Expression<Func<TLookup, TKey>> innerKeySelector = Expression.Lambda<Func<TLookup, TKey>>(Expression.PropertyOrField(l, "Id"), l);

   Expression<Func<T, TLookup, IQueryable<TLookup>>> resultSelector = null;//<---How to compose this

   MethodInfo joinMethod = typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(m => m.Name == "Join" && m.GetParameters().Length == 5).First();
   var genericJoinMethod = joinMethod.MakeGenericMethod(typeof(T), typeof(TLookup), typeof(TKey), typeof(IQueryable<TLookup>));
   var result = genericJoinMethod.Invoke(source, new object[] { source, lookup, outerKeySelector, innerKeySelector, resultSelector });
   return (IQueryable<TLookup>)result;
}

1 个答案:

答案 0 :(得分:5)

我认为应该这样做:

var resultSelector = Expression.Lambda<Func<T, TLookup, TLookup>>(l, s, l);