如果你想同时处理IComparable
和IComparable<>
var OrderByOptions = (from p in typeof(Project).GetProperties()
let type = p.PropertyType
where typeof(IComparable).IsAssignableFrom(type) ||
typeof(IComparable<>).MakeGenericType(type).IsAssignableFrom(type)
select p.Name).ToArray();
请注意,如果您正在执行服务器端排序,则不能保证IComparable
/IComparable<T>
在 SQL 中是相同的。例如:
bool b1 = typeof(IComparable).IsAssignableFrom(typeof(int?));
bool b2 = typeof(IComparable<int?>).IsAssignableFrom(typeof(int?));
两者都返回假。但是可以为空的 int 在 SQL 中肯定是可比的。
也许白名单会更好。
public static readonly HashSet<Type> ComparableTypes = new HashSet<Type>
{
typeof(bool), typeof(bool?),
typeof(char), typeof(char?),
typeof(string),
typeof(sbyte), typeof(sbyte?), typeof(byte), typeof(byte?),
typeof(short), typeof(short?), typeof(ushort), typeof(ushort?),
typeof(int), typeof(int?), typeof(uint), typeof(uint?),
typeof(long), typeof(long?), typeof(ulong), typeof(ulong?),
typeof(float), typeof(float?),
typeof(double), typeof(double?),
typeof(decimal), typeof(decimal?),
typeof(DateTime), typeof(DateTime?),
typeof(DateTimeOffset), typeof(DateTimeOffset?),
typeof(TimeSpan), typeof(TimeSpan?),
typeof(Guid), typeof(Guid?),
};
var OrderByOptions = (from p in typeof(Project).GetProperties()
let type = p.PropertyType
where ComparableTypes.Contains(type)
select p.Name).ToArray();