Predicate with param

M

Mirek Endys

Is there a possibility to write an Predicate with param?

I need to look for a value in Array, or in List, but this value is variable.
How do I write something like this:

class MyObject
{
public Guid Id;
public string Caption;
}


List<MyObject> _myList = new List<MyObject>()

..... here is code for filling the list.....

now I need somehing like this:

private static bool MatchID(MyObject item, Guid id) // this is
impossible???
{
return (item.Id == id);
}

_myList.Find(MatchID, searchid) // this is impossible.... ????

Must I enumerate the List by foreach or is it possible to do it by another
way.

Thanks
 
M

Mattias Sjögren

_myList.Find(MatchID, searchid) // this is impossible.... ????

Must I enumerate the List by foreach or is it possible to do it by another
way.

You can create an anonymous delegate, something like

_myList.Find(delegate (MyObject item) { item.Id == searchid; });


Mattias
 
J

Jay B. Harlow [MVP - Outlook]

Mirek,
I get the impression that System.Predicate was really intended for anonymous
delegates, rather then actual methods in C# or VB.

Something like:

List<MyObject> _myList = new List<MyObject>();

Guid id = ...

_myList.Find(MatchID, delegate()
{
return (item.Id == id);
}
);


An good introduction to anonymous delegates:
http://msdn.microsoft.com/msdnmag/issues/04/05/C20/default.aspx

--
Hope this helps
Jay [MVP - Outlook]
..NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley - http://www.tsbradley.net


| Is there a possibility to write an Predicate with param?
|
| I need to look for a value in Array, or in List, but this value is
variable.
| How do I write something like this:
|
| class MyObject
| {
| public Guid Id;
| public string Caption;
| }
|
|
| List<MyObject> _myList = new List<MyObject>()
|
| .... here is code for filling the list.....
|
| now I need somehing like this:
|
| private static bool MatchID(MyObject item, Guid id) // this is
| impossible???
| {
| return (item.Id == id);
| }
|
| _myList.Find(MatchID, searchid) // this is impossible.... ????
|
| Must I enumerate the List by foreach or is it possible to do it by another
| way.
|
| Thanks
|
|
|
|
|
|
|
|
|
|
 

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