Find in Generic.List

A

Allan Bredahl

Hi All

I'm trying to use a Generic.List declared as follows (Example):

Public Class MyObj
{
Public String Name;
Public Integer Age;
}


Public Class GenericTest
{

private System.Collections.Generic.List<MyObj> TheList;


Public void Search()
{
string SearchForName = "Michael";
MyObj FoundObj;

FoundObj = TheList.Find(FindByName)
}

private bool FindByName(MyObj obj)
{
if (obj.Name == ???)
return true
else
return false;
}
}

I would like to find instances og MyObj by passing a Name value, but I can't
seem to find out how to make a Predicate that can do just that.

How do I pass the SearchForName to the Delegate/predicate ?????


Anyone has some code that will help me out here


THanks in advance

Allan Bredahl
 
M

Marc Gravell

3 ways via C#; the 3rd is more-or-less what the compiler does with the
2nd - might be useful depending on how you can use inline delegates in
VB.Net (I honestly don't know):

public MyObj Search1(string name) {
foreach (MyObj obj in TheList) if (obj.Name == name) return
obj;
return null;
}
public MyObj Search2(string name) {
return TheList.Find(delegate(MyObj obj) { return obj.Name ==
name; });
}
public MyObj Search3(string name) {
return TheList.Find(new FindByName(name).IsMatch);
}
internal class FindByName {
private string name;
public FindByName(string name) {
this.name = name;
}
public bool IsMatch(MyObj obj) {
return obj.Name == name;
}
}
 
G

Guest

I had the same problem Allan.
I used this solution, by the way Find does not return bool it returns the
found object otherwise null.

Public Class MyObj
{
Public String Name;
Public Integer Age;
}


Public Class GenericTest
{

private System.Collections.Generic.List<MyObj> TheList;


Public void Search()
{
string SearchForName = "Michael";
MyObj FoundObj;

FoundObj = TheList.Find(delegate(MyObj obj){return obj.Name ==
SearchForName ? obj : null ;})
}

}
 

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