views:

440

answers:

2

Hello,

I have a system.collections.generic.list(of ListBox)

I would like to use the collection classes built-in Find method to find a particular ListBox by the Name of the Listbox

I found the following MSDN article

http://msdn.microsoft.com/en-us/library/x0b5b5bc.aspx

This does not work for me because it does not show how to find a SPECIFIC instance in the collection by the collection name.

The example hard codes the search String of "saurus" into the Find predicate. I want to pass in the search name. When I add a variable I the FindListBox function I created I get an error saying the signature doesn't match.

I know I can add a private method to my own class but now I am curious how to implement the Find in the Generic so I can do this.

Seth

+5  A: 

Assuming you're using C# 3:

string nameToFind = "saurus";
ListBox found = list.Find(x => x.Name == nameToFind);

For C# 2:

string nameToFind = "saurus";
ListBox found = list.Find(delegate (ListBox x) { return x.Name == nameToFind; });

(Yes, this is still hard-coding the value, just for sample purposes. But the nameToFind variable could be a method parameter, or the result of a method call etc.)

Jon Skeet
Thanks for the answer Jon. Gave points to the other guys ... he needs them more than you. ; / )But your answer worked too. Same as his.
Seth Spearman
Yeah, keep up that line of thinking. I can certainly use the points...
David Andres
+1  A: 

The example on MSDN could be extended as follows:

private static ListBox EndsWith(String s, List<ListBox> list)
{
  return list.Find(
    delegate(ListBox l)
    {
      return l.Name.EndsWith(s);
    }
  );
}

This uses an anonymous delegate to perform the search. The reason why you're getting signature errors is that this delegate, which is the same as the EndsWithSaurus method used in the example, must take a single parameter of the type being searched. I haven't tested this, but this is where I'd go. You can further extend on this principle by making this a templated method that takes a List of T and returns T.

Alternatively, you can use lambda expressions in C# 3.0:

list.FirstOrDefault(x => x.Name.EndsWith("something");
David Andres
Thanks. That did it.Seth
Seth Spearman
No need to use `FirstOrDefault` - you can still use `List.Find` with a lambda expression.
Jon Skeet
Does find handle nulls well? Part of the reason I use FirstOrDefault is that I expect there to be circumstances where nothing has matched.
David Andres