Predicate

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Lit

    Predicate

    Hi,

    Can someone explain this:

    <this is from Using generic- By Ludwig Stuyck>

    string nameToFind = "Ludwig Stuyck";
    PersonNameFilte r personNameFilte r = new PersonNameFilte r(nameToFind);

    // Create a new predicate, that uses the FilterByName method to determine
    whether the person has been found

    Predicate<Perso nfilterByName = new
    Predicate<Perso n>(personNameFi lter.FilterByNa me);

    // Find the person in the collection

    Person foundPerson = persons.Find(fi lterByName);

    ?? Are we passing a method to a method or what

    ?? is this similar to anonymous methods.

    ?? can not see the fully understand it or see the full power yet, but I
    know/heard it is very powerful

    Thanks

    Lit.


  • AlexS

    #2
    Re: Predicate

    Look at Predicate Generic Delegate in MSDN, which provides basic sample.

    Extract from sample
    // To find the first Point structure for which X times Y
    // is greater than 100000, pass the array and a delegate
    // that represents the ProductGT10 method to the Shared
    // Find method of the Array class.
    Point first = Array.Find(poin ts, ProductGT10);

    // Note that you do not need to create the delegate
    // explicitly, or to specify the type parameter of the
    // generic method, because the C# compiler has enough
    // context to determine that information for you.

    // Display the first structure found.
    Console.WriteLi ne("Found: X = {0}, Y = {1}", first.X, first.Y);

    Note that you don't need create delegate and you can use in-class method:

    // This method implements the test condition for the Find
    // method.
    private static bool ProductGT10(Poi nt p)
    {
    if (... return false;
    }
    }
    }

    As you can see you pass "method to method" - namely, delegate, which is
    somewhat similat to anonymous method - if to forget that you can use
    ProductGT10 also as standard static method.

    HTH
    Alex


    "Lit" <sql_agentman@h otmail.comwrote in message
    news:OcoqdXPuHH A.4916@TK2MSFTN GP04.phx.gbl...
    Hi,
    >
    Can someone explain this:
    >
    <this is from Using generic- By Ludwig Stuyck>
    >
    string nameToFind = "Ludwig Stuyck";
    PersonNameFilte r personNameFilte r = new PersonNameFilte r(nameToFind);
    >
    // Create a new predicate, that uses the FilterByName method to determine
    whether the person has been found
    >
    Predicate<Perso nfilterByName = new
    Predicate<Perso n>(personNameFi lter.FilterByNa me);
    >
    // Find the person in the collection
    >
    Person foundPerson = persons.Find(fi lterByName);
    >
    ?? Are we passing a method to a method or what
    >
    ?? is this similar to anonymous methods.
    >
    ?? can not see the fully understand it or see the full power yet, but I
    know/heard it is very powerful
    >
    Thanks
    >
    Lit.
    >
    >
    >

    Comment

    • Marc Gravell

      #3
      Re: Predicate

      The Predicate<Tcan be thought of as a (typed) function pointer, so
      yes this is essentially passing a method to a method; this allows the
      Find method to invoke the method on each item (Person) in turn, and
      see if it is a match (by returning true). How you construct the
      predicate is where it gets fun; the way shown here is obviously using
      a class definition - but as you can see (I imagine the
      PersonNameFilte r code is shown) this is a pain, and not very versatile
      as you need more and more classes / methods every time you have a
      different filter. Anonymous methods are far more concise, but do
      *exactly* the same thing; it is the C# compiler that writes the
      PersonNameFilte r class and FilterByName method (although the names
      will be different of course).
      This allows us to simply use:
      Person found = persons.Find(de legate (Person p) {return p.Name ==
      nameToFind;});

      In C# 3.0 (.NET 3.5) we can use Lambda expressions to do the same even
      tidier:
      Person found = Find(p=>p.Name= =nameToFind);

      To illustrate what I meant about function pointers (the first part),
      internally (courtesy of reflector) the List<T>.Find method is shown
      below.

      Marc

      public T Find(Predicate< Tmatch)
      {
      if (match == null)
      {

      ThrowHelper.Thr owArgumentNullE xception(Except ionArgument.mat ch);
      }
      for (int i = 0; i < this._size; i++)
      {
      if (match(this._it ems[i]))
      {
      return this._items[i];
      }
      }
      return default(T);
      }

      Comment

      • Lit

        #4
        Re: Predicate

        Thanks AlexS and Marc

        I have a headache but trying to see the big picture.
        Please let me see If I understand you both here.

        we are invoking a method passing parameters and one of them is a pointer to
        a method.

        So If I have a generic method that is mostly the same but one element of it
        needs a specialized Method ( the one I am passing ) then this is where it is
        useful???

        do you have few problems where you see this as a solution the only good
        solution or generic solution. the string theory of everything?

        Is this most useful for collections?

        Is this useful for Mathematical problems.

        where else have you seen this useful? Artificial Intelligence, super
        dynamic polymorphic systems or what?

        I am not at the point of pulling my hair yet... but getting gray.

        Enlighten me please,

        Thank you,

        Lit


        "Lit" <sql_agentman@h otmail.comwrote in message
        news:OcoqdXPuHH A.4916@TK2MSFTN GP04.phx.gbl...
        Hi,
        >
        Can someone explain this:
        >
        <this is from Using generic- By Ludwig Stuyck>
        >
        string nameToFind = "Ludwig Stuyck";
        PersonNameFilte r personNameFilte r = new PersonNameFilte r(nameToFind);
        >
        // Create a new predicate, that uses the FilterByName method to determine
        whether the person has been found
        >
        Predicate<Perso nfilterByName = new
        Predicate<Perso n>(personNameFi lter.FilterByNa me);
        >
        // Find the person in the collection
        >
        Person foundPerson = persons.Find(fi lterByName);
        >
        ?? Are we passing a method to a method or what
        >
        ?? is this similar to anonymous methods.
        >
        ?? can not see the fully understand it or see the full power yet, but I
        know/heard it is very powerful
        >
        Thanks
        >
        Lit.
        >
        >

        Comment

        • Jon Skeet [C# MVP]

          #5
          Re: Predicate

          Lit <sql_agentman@h otmail.comwrote :

          <snip>
          ?? Are we passing a method to a method or what
          >
          ?? is this similar to anonymous methods.
          >
          ?? can not see the fully understand it or see the full power yet, but I
          know/heard it is very powerful
          Okay, there are three concepts here:

          1) Delegates
          2) Generics
          3) Anonymous methods

          Anonymous methods are *one* way of creating delegate instances.
          You don't have to bring in generics to understand delegates, but once
          you understand delegates and generics separately, the two work together
          very easily.

          Here's my article about delegates (and events) - hope it helps:
          Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.


          --
          Jon Skeet - <skeet@pobox.co m>
          http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
          If replying to the group, please do not mail me too

          Comment

          • Bob Johnson

            #6
            Re: Predicate

            RE:
            << where else have you seen this useful >>

            I have a Windows Forms application that maintains a collection of "people"
            objects with properties for FirstName, LastName, SSN, etc. I provide the
            users with the ability to search for people by FirstName, LastName, (or
            both), SSN, etc.

            As the user types, I display a list of people that match what has been typed
            in. I make use of the Predicate<Tdele gate to search the "master
            collection" of people objects. Different methods search for a match based on
            the property the user is searching [actively typing] on.

            Very useful. It's not rocket surgery - quite simple once understood.


            Comment

            • Marc Gravell

              #7
              Re: Predicate

              Most of your questions relate to the usage of delegates (not generics
              nor anonymous methods).

              The biggest use (by far) of delegates is to support events, but this
              isn't what is happening here. The delegate-as-a-function-pointer
              scenario is useful (especially when writing re-usable base classes,
              such as collections) when we know a "pattern of behavior", but not the
              details - i.e. (in this case) "return true if the given item is what
              we are looking for". But delegates aren't the only option here -
              interfaces could be used equally, i.e. compare and contrast:

              public delegate bool Predicate<T>(T value); // standard definition
              public interface IPredicate<T{bo ol Match(T value);} // i'm making
              this up...

              Not much real difference - the Find method could equally accept an
              IPredicate<Tand call the Match() method each time. In fact, this
              duality is quite common - look at IComparer<Tand Compison<T(both
              used typically to provide custom sorting). I'd struggle to give many
              reasons why either is much better... delegates allow for anonymous
              syntax (but that is a function of the compiler; if delegates didn't
              exist perhaps there would be "anonymous interface implementation" ...),
              and can be used on static methods (compares perhaps to a singleton for
              a "static" concrete interface implementation) ... compatible delegates
              can be created from multiple different (but suitable) methods on the
              same class (compare perhaps to multiple nested private Types, each
              implementing the interface differently).

              Not sure I really answered much there...

              Marc

              Comment

              • Lit

                #8
                Re: Predicate

                Bob,

                I see a good example here, but need a few lines of details.

                Lets say I am using your program and typing the first character of a last
                name
                then what do you ( your application) do.

                Are you calling just one method passing it a method as a parameter telling
                it to search by last name.

                please give me a bit more detail to help me understand this.

                you are right once I understand rocket science its easy.

                Thank you,

                Lit



                "Bob Johnson" <A@B.COMwrote in message
                news:eeMi0GQuHH A.1208@TK2MSFTN GP05.phx.gbl...
                RE:
                << where else have you seen this useful >>
                >
                I have a Windows Forms application that maintains a collection of "people"
                objects with properties for FirstName, LastName, SSN, etc. I provide the
                users with the ability to search for people by FirstName, LastName, (or
                both), SSN, etc.
                >
                As the user types, I display a list of people that match what has been
                typed in. I make use of the Predicate<Tdele gate to search the "master
                collection" of people objects. Different methods search for a match based
                on the property the user is searching [actively typing] on.
                >
                Very useful. It's not rocket surgery - quite simple once understood.
                >

                Comment

                • Jon Skeet [C# MVP]

                  #9
                  Re: Predicate

                  Bob Johnson <A@B.COMwrote :

                  <snip>
                  Very useful. It's not rocket surgery - quite simple once understood.
                  Do you include anonymous types using captured variables in "quite
                  simple"? :)

                  --
                  Jon Skeet - <skeet@pobox.co m>
                  http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
                  If replying to the group, please do not mail me too

                  Comment

                  • Jon Skeet [C# MVP]

                    #10
                    Re: Predicate

                    Marc Gravell <marc.gravell@g mail.comwrote:
                    Most of your questions relate to the usage of delegates (not generics
                    nor anonymous methods).
                    Oi! Stop stealing my thoughts! :)
                    The biggest use (by far) of delegates is to support events, but this
                    isn't what is happening here.
                    It's worth pointing out that although events are probably the biggest
                    use of delegates in C# 1 and 2 (closely followed by starting threads
                    and using Control.Invoke/BeginInvoke), I'm expecting C# 3 and LINQ will
                    change the balance a lot over time. Even .NET 2.0 encourages more use
                    of delegates, particularly for things like comparisons used in sorting.
                    List<Thas some nice features on that front.

                    I'd urge all C# 1 and 2 developers to make sure they're really
                    comfortable with delegates now, before C# 3 is released: that way
                    you'll be a lot better prepared come the revolution.

                    --
                    Jon Skeet - <skeet@pobox.co m>
                    http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
                    If replying to the group, please do not mail me too

                    Comment

                    • Bob Johnson

                      #11
                      Re: Predicate

                      I was being sarcastic...

                      .....thus I said it's like "rocket surgery" which conveys that I don't even
                      understand how to say "rocket science" or "brain surgery" without confusing
                      them. not as funny when it has to be explained...

                      :-)





                      Comment

                      • Jon Skeet [C# MVP]

                        #12
                        Re: Predicate

                        Bob Johnson <A@B.COMwrote :
                        I was being sarcastic...
                        >
                        ....thus I said it's like "rocket surgery" which conveys that I don't even
                        understand how to say "rocket science" or "brain surgery" without confusing
                        them. not as funny when it has to be explained...
                        I didn't take it as sarcasm because until you bring in anonymous
                        methods and captured variables etc, delegates really *aren't* very
                        complicated, in my view. They take a little while to get your head
                        round the basic concept, but after that it's not a problem.

                        Captured variables, on the other hand... incredibly useful, but so easy
                        to get wrong. Hopefully we'll all become better at using them over
                        time, myself very much included.

                        --
                        Jon Skeet - <skeet@pobox.co m>
                        http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
                        If replying to the group, please do not mail me too

                        Comment

                        • Marc Gravell

                          #13
                          Re: Predicate

                          I promise to give them back afterwards...


                          Comment

                          Working...