I need to create a method to select the firts property from a collection with the specified type.
I created a method similar to this (I removed some parts for brevity):
public static IQueryable<TResult> SelectFirstPropertyWithType<T, TResult>(this IQueryable<T> source) { // Get the first property which has the TResult type var propertyName = typeof(T).GetProperties() .Where(x => x.PropertyType == typeof(TResult)) .Select(x => x.Name) .FirstOrDefault(); var parameter = Expression.Parameter(typeof(T)); var body = Expression.Convert(Expression.PropertyOrField(parameter, propertyName), typeof(TResult)); var expression = Expression.Lambda<Func<T, TResult>>(body, parameter); return source.Select(expression); }
And I can call this method the following:
List<Person> personList = new List<Person>();
Everything is working fine.
But I do not want to set the first type of the argument as Person , because the compiler can infer this type of argument from the source of the collection. Is there a way to call the method as follows:
.SelectFirstPropertyWithType<int>()
The problem is that I need the T parameter inside my method, and I don't want to create Func with reflection at runtime.
Thanks.
source share