传递一个lambda表达式作为参数的方法? [英] Passing a lambda expression as parameter to a method?

查看:1179
本文介绍了传递一个lambda表达式作为参数的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来这会是一个共同的要求,但我找不到解决这个任何地方。



我有一个方法,它将排序依据根据传递给它的参数的集合。



我想一个排序依据中的内容传递给方法,但不知道如何做到这一点。



我已经试过



我试过用细绳开关(例如,如果你通过名称它会击中情况它的名字订单),但这种感觉哈克'和不必要的



我知道这有点像 Func键< TEntity,TResult> ,但我不能很。破解它



伪代码:

  GetOrderedCollection([不知道]排序依据)
{
返回collection.OrderBy(排序依据);
}


解决方案

排序依据是一个扩展方法,以下签名:

 公共静态IOrderedEnumerable< TSource>排序依据< TSource,TKEY的>(
本的IEnumerable< TSource>源,
Func键< TSource,TKEY的>的KeySelectors

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



所以你的方法需要一个函数功能作为它的参数,其中TSource是List类型,TKEY的是你的lambda返回的类型。
的一个例子是:



 公共无效的方法和LT; TSource,TKEY的>(列表< TSource>列表中,Func键< TSource,TKEY的> FUNC)
{
...
IOrderedEnumerable< TSource> orderedEnumerable = list.OrderBy(FUNC);
}



编辑:
我还注意到在你的示例代码,你声明你的方法无效,那么卜你想返回IOrderedEnumerable。
如果你想获得的有序集合回来了,你的方法需要有至少一个IEnumerable类型(但会破坏责令目的,因为IEnumerables不保证秩序。更可能的实施将返回一个列表< TSource> 并调用 list.OrderBy(FUNC).ToList()


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

解决方案

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()

这篇关于传递一个lambda表达式作为参数的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆