How to construct Order By Expression dynamically in Entity Framework?

前端 未结 2 441
盖世英雄少女心
盖世英雄少女心 2020-11-30 05:39

I used the following methods to construct Order By Expression. Original Source

It is really slick. The downside is it only works if Property is

2条回答
  •  执念已碎
    2020-11-30 06:33

    I have, IMHO, a simpler solution:

    public static IOrderedQueryable Sort(this IQueryable source, bool ascending , string sortingProperty)
    {
        if (ascending)
            return source.OrderBy(item => item.GetReflectedPropertyValue(sortingProperty));
        else
            return source.OrderByDescending(item => item.GetReflectedPropertyValue(sortingProperty));
    }
    
    private static object GetReflectedPropertyValue(this object subject, string field)
    {
        return subject.GetType().GetProperty(field).GetValue(subject, null);
    }
    

    The usage is:

    myQueryableCollection.Sort(ascending: true, "Name")
    

    Of course, the PropertyExist() helper is a great addition...

提交回复
热议问题