How to use an inline delegate with the Find method on collections
C#, C# Language August 23rd, 2006C# provides a very powerful and concise method of locating items in collections. The find Method on collections and generic lists (and other collection type classes) take a predicate as the parameter. To the beginner programmer the power of this parameter is not obvious.
Lets take a simple collection of objects, MyClass defined as follows:
class MyClass
{
public int Id;
public String Name;
}
and an associated collection, in this cas a simple generic list.
class MyClassCollection : List<MyClass>
{
...
}
Implementing a coupl of methods to Find by Id or name is really simple with the Find method. We create an inline delegate that returns a boolean true of false if a match occurs. e.g.
public MyClass FindByID(int id)
{
return this.Find(
delegate(MyClass itemInCollection)
{
return (itemInCollection.Id == id);
}
);
}
The FindByID method returns an instance of MYClass that the Find method locates.
The FindMethod takes and inline delegate that expects the current instance that the find method is looking at to be passed in (itemInCollection).
As the delegate is inline, it can reference the id parameter passed into the FindByID method and this can be used in the comparison.
An alternative to method of implementation is to pass as the predicate, a equality method that is defiend on the collection class, but this would mean that the value you are trying to find would have to be set as public field on the collecttion class, and therefore mutliple threads could not search the collection at the same time.
Below is an example of the class with a FindByName delegate as well.
class MyClassCollection : List<MyClass>
{
public MyClass FindByID(int id)
{
return this.Find(
delegate(MyClass itemInCollection)
{
return (itemInCollection.Id == id);
}
);
}
public MyClass FindByID(string name)
{
return this.Find(
delegate(MyClass itemInCollection)
{
return (itemInCollection.Name == name);
}
);
}
}
November 29th, 2006 at 4:35 pm
Is there a way to use an inline delegate without creating a class that inherits from List?
November 29th, 2006 at 4:41 pm
Yes, this is just an example.
change to
someListInstance.Find(
delegate(CollectionItemType itemInCollection)
{
return (itemInCollection.Name == name);
}
);
where CollectionItemType is the type of item you want to find and someListInstance is the collection you are searching.
February 16th, 2007 at 12:38 pm
I was going to leave a comment about it not working but the dumb security code messed up my post and now I can’t be bothered entering and editing the post again. But…
Error message: Unable to cast object of type ‘System.Collections.Generic.List`1[PensionFundConsultant]‘ to type ‘PensionFundConsultantCollection’.
On this line:
PensionFundConsultantCollection PensionFunds = (PensionFundConsultantCollection)(List)Cache["PensionFunds"];
I can make the collection class but I can’t create an instance of it.