开发者

Linq and order by

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 )
          re开发者_JAVA百科s = 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 ?


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.


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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜