Reputation: 94
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?
Upvotes: 1
Views: 2972
Reputation: 1542
Not sure exactly what you're looking to achieve by "de-sugaring" the originals, but you can remove the redundant funcs
var resultSet4 = products.Where(Filter).OrderByDescending(OrderAndSelect).Select(orderAndSelect);
static bool Filter(string p) { return p.StartsWith("M"); }
static string OrderAndSelect(string p) { return p; }
In terms of expansion I think this covers the most expanded case (unless you separate Order and Select).
Perhaps an explanation of why you want to do this would be helpful tho?
Upvotes: 0
Reputation: 726639
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
Upvotes: 3