根据名称确定 IQueryable 列类型

Determine IQueryable column type based on name

我有一个 iQueryable 数据集。

我希望能够根据名称判断数据类型

我正在对视图模型执行 linq 查询,我希望从结果查询中按名称获取列的类型

IQueryable q = ...;
if (q.ElementType.GetProperty("PropertyName").PropertyType == typeof(int))
{
    // PropertyName is an integer property
    . . .
}

你问的不是很清楚...我希望你不想发现 IdIdChildChildIdint 只是因为它们包含单词 Id...

为了更理智"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);
    }
}

像这样使用它:

Type type = query.TypeOf("Id");

或者如果您使用的是非通用 IQueryable,请使用@shevchenko 的解决方案