how to allow the user to choose how to sort his list using a variable?

后端 未结 4 1250
攒了一身酷
攒了一身酷 2021-01-26 10:32

the information that the user enters can be sorted in many ways ascending and descending and i\'m trying to make the user choose how he want to see the data:

so is there

4条回答
  •  我在风中等你
    2021-01-26 11:02

    If I understood your problem right, that you want to sort dynamically with the property name which is stored in emsort.Text, then you can use Expressions:

    assuming empName is IEnumerable, then use this:

    private static Func GetSortable(string sortablePoperty)
        {
            var param = Expression.Parameter(typeof(Employee), "e");
            var member = Expression.Property(param, sortablePoperty);
            Expression memberAsObject = Expression.Convert(member, typeof(object));
            return Expression.Lambda>(memberAsObject, param).Compile();
        }
    

    then use it:

    string sort=emsort.Text ;
    empName.OrderBy(GetSortable(sort));
    

    if empName is IQueryable, then use this:

    private static Expression> GetSortable(string sortablePoperty)
        {
            var param = Expression.Parameter(typeof(Employee), "e");
            var member = Expression.Property(param, sortablePoperty);
            Expression memberAsObject = Expression.Convert(member, typeof(object));
            return Expression.Lambda>(memberAsObject, param);
        }
    

提交回复
热议问题