5

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 ?

Kumar
  • 9,481
  • 10
  • 74
  • 126
  • Likely you can use something from this famous question: [Dynamic LINQ OrderBy](http://stackoverflow.com/questions/41244/dynamic-linq-orderby). Marc Gravell has a great answer with a bunch of upvotes. – p.campbell Oct 14 '10 at 22:24

2 Answers2

1

Just pass the sort key as a delegate:

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

The drawback is that it requires an extra type parameter...

Thomas Levesque
  • 270,447
  • 59
  • 580
  • 726
1

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.

Eamon Nerbonne
  • 43,645
  • 18
  • 92
  • 161