Can someone please help to explain what's happening in the following code? Many thanks! The result is meo but I don't understand how the two 'where' work in this context.
public class Cat {
public string Text { get; set; }
public Cat Where(Func<Cat,bool> cond) {
return new Cat {
Text = cond(this)? this.Text.ToUpper(): this.Text.ToLower()
}; }
}
public static class CatExtensions {
public static T Select<T>(this Cat cat, Func<Cat,T> proj)
{
return proj(cat);
}
}
var moggy = new Cat { Text = "Meo" };
var result = from m in moggy
where true
where false
select m.Text;
It's easier to understand if you look at the method-chaining syntax version of that expression:
moggy
.Where(m => true) // returns new Cat { Text = "MEO" }
.Where(m => false) // returns new Cat { Text = "meo" }
.Select(m => m.Text); // returns "meo"
from a in B where E
is considered the same as B.Where(a => E)
.
Because of the fact that the class defines its own Where
methods, these are used instead of those defined by Linq, as instance methods are always chosen over extension methods if available. Also those methods aren't applicable anyway.
The first returns an all uppercase MEO cat, then the second acts on that and returns an all lowers case meo cat.
The select is an extension method and applies the delegate to that last object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With