Delegates, not anonymous methods

R

RobinS

I can do this in VB:

For Each fld As Field In _
fieldList.FindAll(AddressOf SearchSelOrKeyNotID)
'do stuff here
Next

where the function is defined:

Private Shared Function _
SearchSelOrKeyNotID(ByVal f As Field) As Boolean
Return Not f.IsIdentity _
AndAlso (f.IsSelected OrElse f.IsKey)
End Function

And fieldList is defined:

Dim fieldList As List(Of Field)

In C#, I can do this with an anonymous method like this (which is cool):

foreach (Field fld in fieldList.FindAll(
delegate(Field f)
{
return (Not f.IsIdentity && (f.IsSelected || f.IsKey));
}))
{
//do stuff
}

where fieldList is defined as:

List<Field> fieldList;

However, I want to use this repeatedly, so I want to know how to use a
function, the way I do in VB. I would appreciate any help you can give me.
(And I hope I got all those pesky curly braces and semi-colons right.)

Thanks in advance,
Robin S.
 
M

Marc Gravell

Note that there are conversion tools around - or you can simply
compile it (from VB) and look in "reflector" to see how the same code
is written in VB.Net and C#. But it should be something like below.

Marc

// field declaration
List<Field> fieldList;
// enumeration
void Test() {
foreach(Field fld in fieldList.FindAll(SearchSelOrKeyNotID)) {
// do stuff here
}
}
// predicate
private static bool SearchSelOrKeyNotID(Field f) {
return !f.IsIdentity && (f.IsSelected || f.IsKey);
}
 
R

RobinS

Cool. That worked like a charm. It never occured to me to just stick the
function name in as the FindAll parameter.

Robin S.
 
M

Marc Gravell

That is a 2.0 nicety. In 1.1 syntax (give or take the generics) you
would have had to use "new Predicate<Field>(SearchSelOrKeyNotID)".
Both forms are common, especially since the VS designer (bless it)
uses the long version, as does the VS editor when using [Tab] to auto-
create a handler following "+=". Presumably this is to pre-emptively
disambiguate, but for the latter I usually trim it afterwards... I
wouldn't touch the designer code, though (it can be fussy...).

Marc
 
R

RobinS

I'm glad I'm using .Net 2.0. But it's always good to know some 1.1 in case
it comes up somewhere.

I wouldn't touch the designer code. I'd never remember to go change it
again after I regenerated it!

Thanks again,
Robin S.
 

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