Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# where and select

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;
like image 264
user3735871 Avatar asked Mar 15 '23 06:03

user3735871


2 Answers

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"
like image 103
JLRishe Avatar answered Mar 29 '23 12:03

JLRishe


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.

like image 31
Jon Hanna Avatar answered Mar 29 '23 12:03

Jon Hanna