Strongly typed dynamic Linq sorting

前端 未结 4 1803
被撕碎了的回忆
被撕碎了的回忆 2020-12-01 02:23

I\'m trying to build some code for dynamically sorting a Linq IQueryable<>.

The obvious way is here, which sorts a list using a string for the field name
http

4条回答
  •  感动是毒
    2020-12-01 02:49

    The easiest way to do this would be to have your AddSort() function take an Expression> instead of just a Func. This allows your sort method to inspect the Expression to extract out the name of the property that you want to sort on. You can then store this name internally as a string, so storing is very easy and you can use the sorting algorithm you linked to, but you also get type safety and compile time checking for valid property names.

    static void Main(string[] args)
    {
        var query = from m in Movies select m;
    
        var sorter = new Sorter();
        sorter.AddSort("NAME", m => m.Name);
    }
    
    class Sorter
    {
        public void AddSort(string name, Expression> func)
        {
            string fieldName = (func.Body as MemberExpression).Member.Name;
        }
    }
    

    In this case, i've used object as the return type of the func, because its easily automatically convertible, but you could implement that with different types, or generics, as appropriate, if you require more functionality. In this case, since the Expression is just there to be inspected, it doesn't really matter.

    The other possible way is to still take a Func, and store that in the dictionary itself. Then, when it comes to sorting, and you need to get the value to sort on, you can call something like:

    // assuming a dictionary of fields to sort for, called m_fields
    m_fields[fieldName](currentItem)
    

提交回复
热议问题