Are predicates worth it?

D

David Veeneman

I've been looking at predicate delegates in connection with List<T> search
methods. My initial reaction is that the mechanism looks cumbersome, to the
point where I'm wondering if it's not just simpler to stick with a foreach
loop.

If I understand List<T> search predicates correctly, I'll need to write a
predicate, which is no big deal. But I will also need a member variable to
set the value of the search criteria that the predicate uses.

In other words, if my search criteria is fixed (like the 'ends in -saurus'
example in MSDN), then I only need the predicate. But if I want to create an
'ends in whatever' predicate, I have to create a string member variable to
contain the 'ends in' criteria that is to be used for the search. The
predicate uses the value of the member variable to make its comparison.

Here's my question: Is it worth it? What do I gain over writing a method
with a simple foreach loop to do the search? Thanks.
 
W

William Stacey [MVP]

Guess it just depends on which you prefer:

private List<string> EndsIn(List<string> list, string value)
{
// Using FindAll predicate
return list.FindAll(delegate(string s)
{
return s.EndsWith(value);
});
}

private List<string> EndsIn2(List<string> list, string value)
{
// Using Foreach
List<string> list2 = new List<string>();
foreach ( string s in list )
{
if ( s.EndsWith(value) )
list2.Add(s);
}
return list2;
}

--
William Stacey [MVP]

message | I've been looking at predicate delegates in connection with List<T> search
| methods. My initial reaction is that the mechanism looks cumbersome, to
the
| point where I'm wondering if it's not just simpler to stick with a foreach
| loop.
|
| If I understand List<T> search predicates correctly, I'll need to write a
| predicate, which is no big deal. But I will also need a member variable to
| set the value of the search criteria that the predicate uses.
|
| In other words, if my search criteria is fixed (like the 'ends in -saurus'
| example in MSDN), then I only need the predicate. But if I want to create
an
| 'ends in whatever' predicate, I have to create a string member variable to
| contain the 'ends in' criteria that is to be used for the search. The
| predicate uses the value of the member variable to make its comparison.
|
| Here's my question: Is it worth it? What do I gain over writing a method
| with a simple foreach loop to do the search? Thanks.
|
| --
| David Veeneman
| Foresight Systems
|
|
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top