-1

i want to query result and display in order based on Id,Nam,Phone and Email can anyone help me how to do it. expected result

table1result=> table1.OrderBy(c => c.Id).ThenBy(c => c.Name).ThenBy(c => c.table2.Name).ThenBy(c=>c.table2.Phone)

below is sample code which results in

  Func<IQueryable<T>, IOrderedQueryable<T>> orderExpression = o => o.OrderBy(a => a.Id);
switch(case)
{
 case "Id" : orderExpression = o => o.OrderBy(a => a.Id);
break;
    case "name" : orderExpression = o => o.OrderBy(a => a.Name);
break;
   case "phone" : orderExpression = o => o.OrderBy(a => a.table2.phone);
break;
.
.
.
.
}
which result in 
table1result=> table1.OrderBy(a => a.Id);

TylerH
  • 20,799
  • 66
  • 75
  • 101

1 Answers1

2

I wrote an IQueryable<T> extension and maybe that would help in your case:

public static class QueryableExtensions
{
    public static IQueryable<T> SortBy<T>(this IQueryable<T> source, 
        IEnumerable<string> fieldsToSort)
    {
        Expression expression = source.Expression;
        bool firstTime = true;

        foreach (var f in fieldsToSort)
        {
            // { x }
            var parameter = Expression.Parameter(typeof(T), "x");

            // { x.FIELD }, e.g, { x.ID }, { x.Name }, etc
            var selector = Expression.PropertyOrField(parameter, f);

            // { x => x.FIELD }
            var lambda = Expression.Lambda(selector, parameter);

            // You can include sorting directions for advanced cases
            var method = firstTime
                ? "OrderBy" 
                : "ThenBy";

            // { OrderBy(x => x.FIELD) }
            expression = Expression.Call(
                typeof(Queryable), 
                method,
                new Type[] { source.ElementType, selector.Type },
                expression, 
                Expression.Quote(lambda)
            );

            firstTime = false;
        }

        return firstTime 
            ? source
            : source.Provider.CreateQuery<T>(expression);
    }

}

So this extension method will apply the list of fields to sort on an IQueryable source with either "OrderBy" (if it's first time) or "ThenBy" (otherwise).

Then you can use it like:

var table1Result = table1
    .SortBy(new string[] { "Id", "Name", "Phone" });
David Liang
  • 20,385
  • 6
  • 44
  • 70
  • Please update the code to handle both ASC & DESC order accordingly. It will be very helpful. – Nadim Hossain Sonet Oct 23 '22 at 06:33
  • @NadimHossainSonet: you can kind of check out my other post (especially in Bonus section) about how to implement server side paging and searching with DataTables:https://stackoverflow.com/a/63000348/2410655. I think you can get some ideas from there. – David Liang Oct 24 '22 at 07:46