【问题标题】:pass lambda expression as method parameter将 lambda 表达式作为方法参数传递
【发布时间】:2013-04-08 10:19:36
【问题描述】:

我想创建以下方法,它接受一个 lambda 表达式并通过它对数据进行排序。我似乎无法正确设置它。

在哪里看起来像这样???是 lambda 表达式:

public static MyList<T> PageAndSort<T>(this IEnumerable<T> data, ???)

会这样使用:

MyList.PageAndSort(List<MyEntity> data, x=>x.ChildEntity.Name)

【问题讨论】:

  • 标签说 c# .. 所以我们可以假设:P

标签: c# lambda expression


【解决方案1】:

LINQ 有一个非常相似的方法:OrderBy。看它的签名并模仿它:

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

适用于您的案例:

public static MyList<TSource> PageAndSort<TSource, TKey>(
    this IEnumerable<TSource> data,
    Func<TSource, TKey> keySelector
)

Func&lt;T, TResult&gt; 是一个具有T 类型参数的委托,它返回一个TResult。

【讨论】:

    【解决方案2】:

    使用Action&lt;T&gt; 或Func&lt;T&gt; 取决于您是否需要返回参数。

    所以:

    public static MyList<T> PageAndSort<T>(this IEnumerable<T> data, Action<T> sortBy)
    

    其中T 被替换为您要排序的类型,例如sting 等。

    【讨论】:

    • Grrr,它不会让我添加 Action 注意:Action 后面有一个 类型。
    • Func&lt;T&gt; 没有输入,Action&lt;T&gt; 也不适合,因为您需要一个可用作排序键的结果。
    猜你喜欢
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多