Linq and order by

I have a generic class that can use the 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);
   }
}

OrderBy can be of different types

eg.

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

The goal is to make orderBy an argument, not bake it in

any ideas?

+5
source share
2 answers

Do not pass arguments OrderByto a function that converts IEnumerable(or IQueryable, as it may be).

Changing your example for this leads to 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
    }
}

, someMethod, , (, , ) .

+1

:

 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);
   }
}

, ...

+1

All Articles