c# - Passing type members generically to operate on generic collection -


i'm creating function take ienumerable, conduct grouping, ordering, take top n elements, , return list of elements. may more later on, that's why want make function , not use linq directly.

i rely on anonymous delegate specify members of type t used group , sort collection.

    public ienumerable<t> getlist(ienumerable<t> collection, func<t, object> groupby, func<t, object> orderby, int howmany)     {         var group = collection             .groupby(groupby)             .select(x => x.orderby(orderby).take(howmany))             .aggregate((l1, l2) => l1.concat(l2));          return group.tolist();     } 

and use this:

        new collectiongrouppicker<numericdomainobject>().getlist(list, x => x.groupablefield, x => x.orderablefield, 2).tolist(); 

my question - there better way pass member of type t use group , sort by? i'm using object here, there better way?

instead of specifying object should specify group , select keys generic parameters. type automatically inferred usage , caller can specify lambda return type.

public ienumerable<t> getlist<tgroupkey, torderkey>(ienumerable<t> collection,                                                      func<t, tgroupkey> groupby,                                                      func<t, torderkey> orderby,                                                      int howmany) {     var group = collection         .groupby(groupby)         .select(x => x.orderby(orderby).take(howmany))         .aggregate((l1, l2) => l1.concat(l2));     return group.tolist(); } 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -