在扩展方法中修改lambda表达式

时间:2014-02-06 10:24:27

标签: c# .net lambda linq-to-objects func

我正在尝试使用Generics创建一个扩展方法,您可以在其中接收List of 无论什么阶级,例如:

 class User
 {
  public string name {get;set;}
  public int age {get;set;}
  public string lastLogon {get;set;}
 }

我正在尝试构建一个表达式,在该表达式中,您将IEnumerable传递给扩展方法,并指定哪个是字符串日期属性。 (在这种情况下为lastLogon

没有扩展方法它应该是这样的:

userList.OrderBy(x => Convert.ToDateTime(x.lastLogon));

这是我到目前为止所做的:

 public static IEnumerable<TSource> OrderEnumerablebyDatetimeString<TSource,TKey>(
            this IEnumerable<TSource> input, Func<TSource, TKey> funcexpr)
        {
            //modify expression to get the date field and modify the lambda expr
            Expression<Func<TSource, TKey>> expr = ???

            return input.OrderBy(funcexpr);

        }

我的最终分机号码应如下:

userList.OrderEnumerablebyDatetimeString(x => x.lastLogon);

1 个答案:

答案 0 :(得分:3)

这就是我为你所做的:

public static IEnumerable<TSource> OrderEnumerablebyDatetimeString<TSource>(
this IEnumerable<TSource> input, Func<TSource, string> funcexpr)
{
    Func<TSource, DateTime> expr = (x=>Convert.ToDateTime(funcexpr(x)));

    return input.OrderBy(expr);

}

请注意,我删除并更改了一些通用参数,以更准确地反映您拥有的内容。你已经说过你总是传入一个字符串,所以传入的乐趣应该总是返回一个字符串。同样,您为orderby创建的Expression将始终返回DateTime,因此我对其进行了硬编码。

关键位当然是调用传递的Func来从对象中获取日期字符串。

为了更详细地解释(按照注释中的要求)funcexpr(x)调用以x作为参数传入的func。它很像调用任何其他方法,除了你的方法是在一个变量。特别是func已被声明为接受对象并返回string的方法。在这种情况下,字符串是来自对象的日期字符串,在我们的示例中是用户。因此,funcexpr(x)将返回日期字符串,然后按照您的预期转换为DateTime。

我还应该注意到,这是在Linq to Objects上下文中完成和测试的。我假设你正在谈论与List<User>合作的情况。

这里还有一个指向工作样本的链接,包括字符串排序以及证明其正常工作:http://dotnetfiddle.net/r3Lq0P