Predicate in Generic Lists

I

Isaac

Hello,

I'm using the Generic List class in System.Collection.Generics to
implement a strongly-typed list of my own class. I want to implement the
Find methods and have to use the Predicate delegate to do this.

As I understand it: I create a method which returns a bool and takes in
an object of type <T> where <T> is the type that the generic list was
created on.

Then I call the Find method like so:

myList.Find (new Predicate <T> (myFindMethod));

However, I am unclear as to what exactly myFindMethod should be doing -
what does it compare against or search for? Surely it isn't hard coded
to only find one particular item in the list. So what exactly should it do?

Thanks a lot

Isaac
 
O

Oliver Sturm

Isaac said:
I'm using the Generic List class in System.Collection.Generics to
implement a strongly-typed list of my own class. I want to implement the
Find methods and have to use the Predicate delegate to do this.

As I understand it: I create a method which returns a bool and takes in
an object of type <T> where <T> is the type that the generic list was
created on.

Then I call the Find method like so:

myList.Find (new Predicate <T> (myFindMethod));

However, I am unclear as to what exactly myFindMethod should be doing -
what does it compare against or search for? Surely it isn't hard coded
to only find one particular item in the list. So what exactly should it do?

That's really your problem as the implementor :) But (more) seriously,
the way I often use the kind of method that takes a delegate is with an
anonymous delegate. Like this:

List<MyObject> myList = ...

public MyObject MyFindMethod(Guid objId) {
return myList.Find(delegate(MyObject obj) {
return obj.Id == objId;
});
}

In this case, the delegate can directly access the value that was passed
in to the method I'm implementing and use it for the comparison.

If you want to implement the delegate as a reusable method, you'll have
to find a way to tell the delegate what exactly it should do when it's
called. One way to do this could be to encapsulate the delegate in a
class, like this:

public MyObjectIdSearcher {
public MyObjectIdSearcher(Guid searchId) {
this.searchId = searchId;
}
private Guid searchId;

public bool PredicateDelegate(MyObject obj) {
return obj.Id == searchId;
}
}

Then your search method might look like this:

public MyObject MyFindMethod(Guid objId) {
return myList.Find(new Predicate<MyObject>(
new MyObjectIdSearcher(objId).PredicateDelegate
);
}

The advantage of the second approach would be that you'd have reusable
encapsulation of the algorithm used to search for a given MyObject by
its Id.

Hope this helps!


Oliver Sturm
 

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