-1

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

michal.jakubeczy
  • 8,221
  • 1
  • 59
  • 63
Dale Fraser
  • 4,623
  • 7
  • 39
  • 76

2 Answers2

2
IQueryable q = ...;
if (q.ElementType.GetProperty("PropertyName").PropertyType == typeof(int))
{
    // PropertyName is an integer property
    . . .
}
Mark Shevchenko
  • 7,937
  • 1
  • 25
  • 29
0

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

xanatos
  • 109,618
  • 12
  • 197
  • 280