测试实体中的属性是否可以使用orderBy进行排序

时间:2013-08-20 09:27:19

标签: c# linq reflection

我正在使用linq动态来执行动态orderBy。如何仅获取必须具有可比较的类型的实体的属性名称。该实体具有基本类型(字符串,整数)和复杂对象,我无需用户过滤它们。

var OrderByOptions = typeof (Project).GetProperties().Select(x => x.Name).ToList(); //I only want order comparable property names here

var userSelectable = 2;

var pjs = _pjRepo.Projects.Where(x => x.Active == true).OrderBy(OrderByOptions[userSelectable]).ToList();

2 个答案:

答案 0 :(得分:3)

如果您要同时处理IComparableIComparable<>

,请执行此操作
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?));

都返回false。但是可嵌套的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();

答案 1 :(得分:1)

我认为支持order comparability的所有课程都应该实现IComparable及其通用版本:

var OrderByOptions = typeof (Project).GetProperties()
                                     .Where(p=>typeof(IComparable).IsAssignableFrom(p.PropertyType))
                                     .Select(x => x.Name).ToList();