Linq Extension Methods Versus Linq Query Language… DEATHMATCH

Today I was writing out an example of why the extension methods are for the most part better to use than the querying language. Go figure I would find a case where that’s not entirely true. Say you are using these three funcs:

    Func<User, String> userName = user => user.UserName;
    Func<User, Boolean> userIDOverTen = user => user.UserID < 10;
    Func<User, Boolean> userIDUnderTen = user => user.UserID > 10;

As you can see the first one replaces the lamdba expression to get the user name, the second replaces a lamdba expression used to check if the ID is lower than 10, and let’s face it, the third should be pretty easy to understand now.

NOTE: This is a silly example but it works.

    var userList =
      from user in userList
      where userIDOverTen(user)
      select userName;
Versus

    var otherList =
      userList
      .Where(IDIsBelowNumber)
      .Select(userName)

In this example, the second is a little less verbose since the extension method can make full use of the Func, but he Linq expression can’t since it is look just for a Boolean rather than a Func that returns boolean. However, this is where it might be better to use the expression language. Say you already had a method that takes in more than just a user:

    private Boolean IDIsBelowNumber(User user, Int32 someNumber, Boolean doSomething)
    {
      return user.UserID < someNumber;
    }

Note: doSomething is just there because of the where extension method being ok with a method that takes in a user and integer and returns boolean. Kind of annoying for this example.

Now if you look at the Linq query:

    var completeList =
      from user in userList
      where userIDOverTen(user, 10)
      select userName;

You’re good for it. Now the Extension Method:

    var otherList =
      userList
      .Where(IDIsBelowNumber????)
      .Select(userName)

Without a lambda expression, I really can’t call that method. So now what I have to do is create a method that creates a Func based off the original method call.

    private Func<User, Boolean> IDIsBelowNumberFunc(Int32 number)
    {
      return user => IDIsBelowNumber(user, number, true);
    }

And then plug it in:

    var otherList =
      userList
      .Where(IDIsBelowNumberFunc(10))
      .Select(userName)

What does this all mean? You just lost 5 minutes of your life. I hope it was worth it.