I update the following blog and website with C# documentation:
http://aldosalzberg.wordpress.com/
http://www.aldosalzberg.com/
Here’s a few C# snippets from my code on using the Find method for a
list. This should work on anything greater than .NET 1.X. Don’t forget
to include “System.Collection.Generics”.
Let’s start out very simple example: I have a list of integers and I want to locate a given one, say 23,
int idToLocate = 23;
List<int> idList = new List<int>();
idList.Add(idToLocate);
int current = idList.Find(delegate(int myID) { return myID == idToLocate; });
if (current == idToLocate) Console.Write("The ID was found!");
The above example adds the number 23 to a list, and then searches
for it, returning the number itself. More often than not we are
interested not in the item, but on the location of the item on the list
(its index). In that situation we search for the index, not the item
itself:
int idToLocate = 23;
List<int> idList = new List<int>();
idList.Add(idToLocate);
int currentIndex = idList.FindIndex(delegate(int myID) { return myID == idToLocate; });
if (currentIndex == -1) Console.WriteLine("The ID was not found on the list");
else
Console.WriteLine("The ID was found on the list at position " + currentIndex.ToString());
Moving on, I can then use the RemoveAt or Insert methods to manipulate the item to which the current index is pointing.
We are not limited to simple types. In the next example, Object is a
class or struct and myObject1, myObject2 and myObject3 are instances.
Let’s say that the Object class has a property named “Property1″. Let’s
add two objects to a List and then find the first instance and replace
it with the third object:
List<Object> myObjectList = new List<Object>();
Object myObject1 = new Object();
Object myObject2 = new Object();
Object myObject3 = new Object();
myObjectList.Add(myObject1);
myObjectList.Add(myObject2);
int currentIndex = myObjectList.FindIndex(delegate(Object o) { return o.Property1 == myObject1.Property1; });
//if current index is a non-zero index, the item was found
//I can now use remove at and insert to replace that item with another:
myObjectList.RemoveAt(currentIndex);
myObjectList.Insert(currentIndex, myObject3);
We can now start looking at the dinosaurs example above, and it is fairly clear now how, among other things, a string argument to the method is all that is needed to invoke it from FindIndex. The obvious question to ask next, and which currently remains unanswered, is what are the performance implications of either approach not only in terms of the search, but in terms of invoking this external method without the use of a delegate but rather the named string.