Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a lambda expression as parameter to a method?

It seems like it'd be a common requirement, but I cannot find a solution to this anywhere.

I have a method which will OrderBy a collection depending on a parameter passed to it.

I'd like to pass the contents of an 'OrderBy' to the method, but cannot work out how to do it.

What I've Tried

I've tried a switch with a string (i.e. if you pass 'Name' it'll hit the case which orders it by name), but this feels 'hacky' and unnecessary.

I know it's something like Func<TEntity, TResult>, but I can't quite crack it.

PSEUDO CODE:

GetOrderedCollection([NOT SURE] orderBy)
{
  return collection.OrderBy(orderBy);
}

2 Answers

OrderBy is an extension method with the following signature:

public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector
)

(source: https://msdn.microsoft.com/it-it/library/bb534966%28v=vs.110%29.aspx )

so your method needs a Func as its argument, where TSource is the List type, and TKey is the type returned by your lambda. An example would be:

public void Method<TSource, TKey>(List<TSource> list, Func<TSource, TKey> func)
        {
            ...
            IOrderedEnumerable<TSource> orderedEnumerable = list.OrderBy(func);
        }

EDIT: I also noticed that in your example code you declared your method as void, bu then you're trying to return an IOrderedEnumerable. If you want to get the ordered collection back, your method needs to have at least an IEnumerable type (but that would defeat the purpose of ordering it, as IEnumerables do not guarantee order. A more likely implementation would be to return a List<TSource> and call list.OrderBy(func).ToList()

like image 156
BgrWorker Avatar answered Sep 01 '26 18:09

BgrWorker


In it's most generic form, your method would need to look like:

IOrderedEnumerable<T1> GetOrderedCollection<T1, T2>(IEnumerable<T1> collection, Func<T1, T2> orderBy)
{
    return collection.OrderBy(orderBy);
}

T1 being the type of the items in the list and T2 being the type of the property of T1 that you want to order on.

like image 44
David Arno Avatar answered Sep 01 '26 20:09

David Arno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!