【发布时间】:2015-05-21 10:53:03
【问题描述】:
我有一个 iQueryable 数据集。
我希望能够根据名称确定数据的类型。
我正在对视图模型进行 linq 查询,我希望从结果查询中按名称获取列的类型
【问题讨论】:
-
你是指SQL Server类型,还是C#类型?
-
两者都行,我需要通过名称而不是值来确定列是整数还是字符串。
标签: linq types iqueryable
我有一个 iQueryable 数据集。
我希望能够根据名称确定数据的类型。
我正在对视图模型进行 linq 查询,我希望从结果查询中按名称获取列的类型
【问题讨论】:
标签: linq types iqueryable
IQueryable q = ...;
if (q.ElementType.GetProperty("PropertyName").PropertyType == typeof(int))
{
// PropertyName is an integer property
. . .
}
【讨论】:
不清楚你在问什么...我希望你不想发现 Id 和 IdChild 和 ChildId 是 int 只是因为它们包含单词 @987654325 @...
为了更理智的“你给我查询和属性的名称,我给你属性的Type”:
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 的解决方案
【讨论】: