Search code examples
c#linqdelegatesfuncanonymous-methods

Linq Query Expanding


I have a string array named Products & I am working on Anonymous Methods (Lambda Exprs.) & Linq. So first I wrote;

var resultSet1 = from p in products 
                 where p.StartsWith("M") 
                 orderby p descending  
                 select p;

Then I expand it with Lambda Expressions;

var resultSet2 = products
                 .Where(p => p.StartsWith("M"))
                 .OrderByDescending(p => p)
                 .Select(p => p);

Then I expand it with Anonymous Methods;

var resultSet3 = products
                .Where(delegate(string p) { return p.StartsWith("M"); })
                .OrderByDescending(delegate(string p) { return p; })
                .Select(delegate(string p) { return p; });

Then I expand it with Manual Methods and Func<> Delegates;

Func<string, bool> filterFunc = new Func<string, bool>(Filter);
Func<string, string> orderAndSelectFunc = new Func<string, string>(OrderAndSelect);
var resultSet4 = products.Where(filterFunc).OrderByDescending(orderAndSelectFunc).Select(orderAndSelectFunc);

static bool Filter(string p) { return p.StartsWith("M"); }
static string OrderAndSelect(string p) { return p; }

Then I stuck. So my question is; can I expand this a bit more with replacing Func<> delegate with normal delegates? Or something like that?


Solution

  • Then I expand it with Lambda Expressions ...

    The expression .Select(p => p) is unnecessary in fluent syntax. You can remove it.

    Then I expand it with Anonymous Methods

    In this case, lambdas are simply a shortened version of your anonymous methods.

    Can I expand this a bit more with replacing Func<> delegate with normal delegates?

    Yes, you can. Define static methods in your class with signatures matching your Func<>s, and use them instead of anonymous functions or delegates. You can use method group syntax for making delegates to shorten the code:

    private static bool StartsWithM(string s) {
        return s.StartsWith("M");
    }
    private static string PassThrough(string s) {
        return s;
    }
    ...
    var resultSet4 = products
                .Where(StartsWithM)
                .OrderByDescending(PassThrough)
                .Select(PassThrough); // <<== Again, this can be removed