How to return Boolean value from Action Delegate under List.ForEach()
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
publi开发者_Python百科c bool AreSettingChanged()
{
objRpmButtonHolder.RpmButtonCollection.ForEach(btn
=> {
if (btn.IsChanged)
return true;
});
return true;
}
Try this
public bool AreSettingChanged()
{
return objRpmButtonHolder.RpmButtonCollection.Any(b => b.IsChanged);
}
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);
Maybe you are looking for another method, like Find
or Exists
.
public bool AreSettingChanged()
{
return objRpmButtonHolder.RpmButtonCollection.Exists(btn
=> { return btn.IsChanged; });
}
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;
}
精彩评论