Linq 根据名称确定IQueryable列类型
我有一个iQueryable数据集 我希望能够根据名称确定数据的类型Linq 根据名称确定IQueryable列类型,linq,types,iqueryable,Linq,Types,Iqueryable,我有一个iQueryable数据集 我希望能够根据名称确定数据的类型 我正在对视图模型执行linq查询,我希望从结果查询中按名称获取列的类型不清楚您在问什么。。。我真的希望你不想发现Id和IdChild和ChildId都是int,仅仅因为它们包含Id这个词 IQueryable q = ...; if (q.ElementType.GetProperty("PropertyName").PropertyType == typeof(int)) { // PropertyName is a
我正在对视图模型执行linq查询,我希望从结果查询中按名称获取列的类型不清楚您在问什么。。。我真的希望你不想发现
Id
和IdChild
和ChildId
都是int
,仅仅因为它们包含Id
这个词
IQueryable q = ...;
if (q.ElementType.GetProperty("PropertyName").PropertyType == typeof(int))
{
// PropertyName is an integer property
. . .
}
更理智的“你给我查询和属性名称,我给你属性的类型”
:
或者,如果您使用的是非通用的
IQueryable
,请使用@shevchenko的解决方案您指的类型是SQL Server类型,还是C#类型?两者都可以,我需要根据名称而不是值来确定列是整数还是字符串。
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");