1

I have two relevant static methods in UserModel:

public static UserModel GetUserByUsername(String username)
{
    //do something
    return UserModel;
}

and an overload:

public static UserModel GetUserByUsername(String username, DateTime date)
{
    //do something else
    return DiffUserModel;
}

Right now, I can successfully select a

List<UserModel>

by running

... .Select(UserModel.GetUserByUsername)
  .ToList();

This is calling the overloaded method:

public static UserModel GetUserByUsername(String username)

QUESTION:

How can I call the overloaded method and pass in a DateTime parameter using similar syntax?

I'd like to be able to do something like:

... .Select(UserModel.GetUserByUsername , DateTime.Now)
      .ToList();

to get a List generated from the overloaded method.

1
  • Method delegates cannot be partially applied - use lambdas. Commented Jan 27, 2014 at 22:45

3 Answers 3

5

Try using a lambda expression, a type of anonymous method:

.Select(x => UserModel.GetUserByUsername(x, DateTime.Now))
4
  • Actually, anonymous methods were added to C# before lambda expressions. They are both a way to create inline functions but lambda expressions have a simpler syntax that anonymous methods. Commented Jan 27, 2014 at 22:47
  • That's awesome and now I finally get Lambda expressions vs. delegates. A follow on quesiton: How can I pass an existing date time object? I am getting a `The name '...' does not exist in the current context?
    – JSK NS
    Commented Jan 27, 2014 at 22:47
  • @JSKNS Yes you can, as in var someDate = DateTime.Now; var result = list.Select(x => UserModel.GetUserByUsername(x, someDate). I'm not sure why you're getting that error, and without seeing the code, it's hard to say what this issue is.
    – p.s.w.g
    Commented Jan 27, 2014 at 22:50
  • @jmcilhinney Yes, lambdas are type of anonymous method. I didn't mean to imply that they are synonyms.
    – p.s.w.g
    Commented Jan 27, 2014 at 22:53
1

Firstly, you don't say that one method is overloaded and one is not. That method name is overloaded and both methods are overloads.

As for the question:

.Select(new Func<UserModel, string>(s => UserModel.GetUserByName(s, DateTime.Now)))
2
  • Fair note. How would you better differentiate?
    – JSK NS
    Commented Jan 27, 2014 at 22:50
  • If you're asking how to differentiate overloads then the answer is exactly as the system does: by the number and type of the parameters. I would probably refer to those two methods as the overload with one parameter and the overload with two parameters. Commented Jan 28, 2014 at 0:38
0

Just as an alternate solution, since you seem to like method groups:

.Zip(Enumerable.Repeat(DateTime.Now, whatever.Count), UserModel.GetUserByName)

Will probably do the same thing. It's a slightly awkward use of repeat, but it does end up rather simple.

Not the answer you're looking for? Browse other questions tagged or ask your own question.