Accepted answer

to understand the "display class" you have to understand closures. the lambda you pass here is a closure, a special type of method that magically drags in state from the scope of the method it's in and "closes around" it.

...except of course that there's no such thing as magic. all that state has to actually live somewhere real, somewhere that's associated with the closure method and readily available from it. and what do you call the programming pattern where you associate state directly with one or more methods?

that's right: classes. the compiler transforms the lambda into a closure class, then instantiates the class inside the hosting method so the hosting method can access the state in the class.

the only way to not have this happen is to not use closures. if this is really impacting performance, use an old-school for loop instead of a linq expression.


how can i avoid creating this class (his instances and their garbage collecting) when using the any method?

why does the c# compiler creates this class and is there any alternative of any() i can use?

other posters already explained the why part, so the better question would be how can i avoid creation of a closure?. and the answer is simple: if lambda is using only the passed parameters and/or constants, the compiler will not create a closure. for instance:

bool anyclub() { return playercards.any(c => c.suit ==; }

bool anyof(cardsuit suit) { return playercards.any(c => c.suit == suit); }

the first will not create a closure while the second will.

with all that in mind, and assuming you don't want to use for/foreach loops, you can create own extension methods similar to those in system.linq.enumerable but with additional parameters. for this particular case, something like this would work:

public static class extensions
    public static bool any<t, targ>(this ienumerable<t> source, targ arg, func<t, targ, bool> predicate)
        foreach (var item in source)
            if (predicate(item, arg)) return true;
        return false;

and change the code in question to:

var hasbigger =
        (c, opc) => c.suit == opc.suit
             && c.getvalue() > opc.getvalue());

Related Query

More Query from same tag