views:

58

answers:

5

I am trying to implement following thing. I need to return true if any of the button is found to be changed. I don't want any more looping.

Since ForEach is looking for Action Type Delegate. So is it possible to return bool value from within a deletage

public bool AreSettingChanged()
{
    objRpmButtonHolder.RpmButtonCollection.ForEach(btn
        => {
            if (btn.IsChanged)
                return true;
    });
    return true;
}
A: 
public bool AreSettingChanged()
{
    return objRpmButtonHolder.RpmButtonCollection.Exists(btn
        => { return btn.IsChanged; });
}
Alex Reitbort
+5  A: 

Try this

public bool AreSettingChanged() 
{ 
    return objRpmButtonHolder.RpmButtonCollection.Any(b => b.IsChanged);
} 
Daniel Elliott
+1  A: 

Maybe you are looking for another method, like Find or Exists.

leppie
+3  A: 

You can't because that's how the ForEach method is defined. In your case you would be better off using the Any extension method:

bool result = objRpmButtonHolder.RpmButtonCollection.Any(btn => btn.IsChanged);
Darin Dimitrov
@Darin: Nice and simple answer, never thought that we have Any function also available.
Shantanu Gupta
Returning from the delegate won't break the iteration.
Stephen Cleary
@Stephen, that's correct. I will update my answer. Thanks for pointing this out.
Darin Dimitrov
A: 

Best approach would be to use above mentioned Any method, but for more generic approach with returning variables from lambdas you could capture the outside variable and use it as a return result, i.e.:

        public bool AreSettingChanged()
        {
            bool changed = false;
            objRpmButtonHolder.RpmButtonCollection.ForEach(btn
                =>
                {
                    if (btn.IsChanged)
                        changed = true;
                });
            return changed;
        }
Grozz
+1, nice generic solution. Although, in this case, I would really consider a *classic* `foreach` to be more readable than the `ForEach` extension method.
Heinzi
This solution doesn't break the `ForEach` iteration.
Stephen Cleary
Generally it shouldn't. As for this particular problem, I already mentioned that using the classic foreach or any of the extension methods specified above would be better.
Grozz