Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq and order by

Tags:

c#

.net

lambda

linq

I have a generic class which could use a generic OrderBy argument

the class is as follows

 class abc<T> where T : myType
 {
   public abc(....., orderBy_Argument ){ ... }
   void someMethod(arg1, arg2, bool afterSort = false)
   {
       IEnumerable<myType> res ;
       if ( afterSort && orderBy_Argument != null )
          res = src.Except(tgt).OrderBy( .... );
       else
          res = src.Except(tgt);
   }
}

The orderBy could be of various types

e.g.

.OrderBy( person => person.FirstName )
.OrderBy( person => person.LastName )
.OrderBy( person => person.LastName, caseInsensitive etc )

The goal is to make the orderBy an argument rather than bake it in

any ideas ?

like image 332
Kumar Avatar asked Nov 06 '22 07:11

Kumar


1 Answers

Don't pass in the arguments to OrderBy pass in a function which transforms an IEnumerable (or IQueryable, as it may be).

Modifying your example to do so results in the following program:

using System;
using System.Collections.Generic;
using System.Linq;

class abc<T>  {
    Func<IEnumerable<T>,IEnumerable<T>> sorter;
    public abc(Func<IEnumerable<T>,IEnumerable<T>> sorter) {
        this.sorter=sorter ?? (x=>x);
    }
    public void someMethod(IEnumerable<T> src, bool afterSort = false) {
        var res= (afterSort?sorter:x=>x) (src.Skip(5).Take(10));

        Console.WriteLine(string.Join(", ",res.Select(el=>el.ToString()).ToArray()));
    }
}

public class Program {
    static void Main()    {
        var strs = Enumerable.Range(0,1000).Select(i=>i.ToString());

        var myAbc = new abc<string>(
            xs=>xs.OrderByDescending(x=>x.Length).ThenByDescending(x=>x.Substring(1))
        );

        myAbc.someMethod(strs);      //5, 6, 7, 8, 9, 10, 11, 12, 13, 14
        myAbc.someMethod(strs,true); //14, 13, 12, 11, 10, 5, 6, 7, 8, 9
    }
}

Of course, this is a pretty weird ordering and a nonsensical someMethod - but it demonstrates that you can pass in a very flexible sorting delegate (indeed, the delegate could do more than just sort) with only a very short implementation.

like image 139
Eamon Nerbonne Avatar answered Nov 09 '22 14:11

Eamon Nerbonne