I have an iQueryable dataset.
I wish to be able to determine the type of data based on the name.
I am doing a linq query into a view model and I wish to get the type of column by name from the resulting query
I have an iQueryable dataset.
I wish to be able to determine the type of data based on the name.
I am doing a linq query into a view model and I wish to get the type of column by name from the resulting query
IQueryable q = ...;
if (q.ElementType.GetProperty("PropertyName").PropertyType == typeof(int))
{
// PropertyName is an integer property
. . .
}
It isn't exactly clear what you are asking... I do hope you don't want to discover that Id
and IdChild
and ChildId
are int
just because they contain the word Id
...
For a more sane "you give me the query and the name of the property, I give you the Type
of the property":
public static class EnumerableEx
{
public static Type TypeOf<TSource>(this IQueryable<TSource> source, string propertyName)
{
PropertyInfo property = typeof(TSource).GetProperty(propertyName);
return property != null ? property.PropertyType : null;
}
public static Type TypeOf<TSource, TType>(this IQueryable<TSource> source, Func<TSource, TType> property)
{
return typeof(TType);
}
}
Use it like:
Type type = query.TypeOf("Id");
or if you are using the non-generic IQueryable
, use @shevchenko's solution