473,396 Members | 1,722 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Predicate

Lit
Hi,

Can someone explain this:

<this is from Using generic- By Ludwig Stuyck>

string nameToFind = "Ludwig Stuyck";
PersonNameFilter personNameFilter = new PersonNameFilter(nameToFind);

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

Predicate<PersonfilterByName = new
Predicate<Person>(personNameFilter.FilterByName);

// Find the person in the collection

Person foundPerson = persons.Find(filterByName);

?? 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.
Jun 27 '07 #1
12 4579
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(points, 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.WriteLine("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(Point 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" <sq**********@hotmail.comwrote in message
news:Oc**************@TK2MSFTNGP04.phx.gbl...
Hi,

Can someone explain this:

<this is from Using generic- By Ludwig Stuyck>

string nameToFind = "Ludwig Stuyck";
PersonNameFilter personNameFilter = new PersonNameFilter(nameToFind);

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

Predicate<PersonfilterByName = new
Predicate<Person>(personNameFilter.FilterByName);

// Find the person in the collection

Person foundPerson = persons.Find(filterByName);

?? 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.

Jun 27 '07 #2
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
PersonNameFilter 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
PersonNameFilter class and FilterByName method (although the names
will be different of course).
This allows us to simply use:
Person found = persons.Find(delegate (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.ThrowArgumentNullException(ExceptionAr gument.match);
}
for (int i = 0; i < this._size; i++)
{
if (match(this._items[i]))
{
return this._items[i];
}
}
return default(T);
}

Jun 27 '07 #3
Lit
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" <sq**********@hotmail.comwrote in message
news:Oc**************@TK2MSFTNGP04.phx.gbl...
Hi,

Can someone explain this:

<this is from Using generic- By Ludwig Stuyck>

string nameToFind = "Ludwig Stuyck";
PersonNameFilter personNameFilter = new PersonNameFilter(nameToFind);

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

Predicate<PersonfilterByName = new
Predicate<Person>(personNameFilter.FilterByName);

// Find the person in the collection

Person foundPerson = persons.Find(filterByName);

?? 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.


Jun 27 '07 #4
Lit <sq**********@hotmail.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:
http://pobox.com/~skeet/csharp/events.html

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jun 27 '07 #5
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<Tdelegate 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.
Jun 27 '07 #6
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{bool 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

Jun 27 '07 #7
Lit
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:ee**************@TK2MSFTNGP05.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<Tdelegate 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.

Jun 27 '07 #8
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 - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jun 27 '07 #9
Marc Gravell <ma**********@gmail.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 - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jun 27 '07 #10
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...

:-)

Jun 27 '07 #11
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 - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jun 27 '07 #12
I promise to give them back afterwards...
Jun 28 '07 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: hall | last post by:
I accidently overloaded a static member function that I use as predicate in the std::sort() for a vector and ended up with a compiler error. Is this kind of overload not allowed for predicates and...
5
by: matthias_k | last post by:
Hi, I need to sort elements of a std::list using a function predicate, something like: bool predicate( const& M m1, const& M m2 ) { return m1.somedata < m2.somedata; } I tried to call...
2
by: Marco Segurini | last post by:
Hi, I have written the following code: // start code using System; using System.Collections.Generic; using System.Text; namespace MyPredicates
5
by: Peter Olcott | last post by:
I created an object that requires access to another objects data, yet have found no good way to pass this data as a parameter because the member function that requires this data must be a binary...
5
by: Andrew Robinson | last post by:
Any easy answer what is wrong here? private List<string> BodyWords = new List<string>(); string word = "Andrew"; the following causes a compilation error:
3
by: BG | last post by:
Here's my program. { array<Byte> ^buffer = // something int length = Array::FindIndex(buffer, gcnew Predicate<Byte>(&MyClass::isChar13) ); ... } bool MyClass::isChar13(Byte b)
8
by: Jeff S. | last post by:
I was recently advised: << Use List<struct> and Find() using different Predicate delegates for your different search needs.>> What is "Predicate delegate" as used in the above recommendation? ...
2
by: =?iso-8859-1?q?Jean-Fran=E7ois_Michaud?= | last post by:
Hello guys, I was wondering if it was possible to reference a boolean predicate in a variable. Basically I want to do with the boolean predicate what you would do with any other variable; I want...
5
by: Ganesh | last post by:
hi ! Can the predicate function used in std::sort take optional arguments ? For instance. I have a class Point. I create a vector of this and then want to compare the slopes of these points with...
8
by: thomas | last post by:
priority_queue usually uses the greater<intpredicate function. But as you know, we don't always use priority_queue<int>. Actually we may need the "priority_queue<pair<int,int>,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.