سؤال

I'm trying to create an extension method with Generics in which you receive a List of whatever class, for example:

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

I am trying to build an expresion in which you pass to the extension method the IEnumerable and you specify which is the string date property. (In this case lastLogon)

Without extension method It should be something like:

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

This is what I have done so far:

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

        }

My final extension call should look like:

userList.OrderEnumerablebyDatetimeString(x => x.lastLogon);
هل كانت مفيدة؟

المحلول

This is what I've got for you:

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

}

Note that I removed and changed some of the generic parameters to more accurate reflect what you have. You've said you're always passing in a string so the fun you pass in should always return a string. Likewise the Expression you are creating for your orderby will always be returning a DateTime so I have hardcoded that.

The key bit of course is calling the passed Func to get the date string from the object.

To explain that in more detail (as requested in comments) funcexpr(x) is calling the func that you passed in with x as its parameter. Its much like calling any other method except your method is in a variable. Specifically func has been declared to be a method that accepts an object and returns a string. In this case the string is the date string from the object which in our example is a user. So funcexpr(x) will return the date string that is then converted to a DateTime by convert as you would expect.

I should also note for completeness that this was done and tested in a Linq to Objects context. Which I assume since you are talking about working with List<User> is the case.

Also here is a link to a working sample, including a string sort as well to prove its working properly: http://dotnetfiddle.net/r3Lq0P

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top