Reputation: 2371
I cannot return from a ForEach, here is my code:
cards.ForEach(delegate(Card c){
if (c.GetFaceValue().ToString() == card) {
return "Your Card has been located";
}
error:
Cannot convert anonymous method to delegate type '... .Card>' because some of the return types in the block are not implicitly convertible to the delegate return type
the following wont work either, as CheckCard
can only return void:
cards.ForEach(CheckCard);
public string CheckCard(Card c) {
if (c.GetFaceValue().ToString() == card) { // card = global
return "Your Card has been located";
}
}
error:
'string SharedGamesClasses.Hand.CheckCard(SharedGamesClasses.Card)' has the wrong return type
Upvotes: 0
Views: 4016
Reputation: 62248
Looking on the logic provided, I suppose you just gonna terminate iteration as sson as there is Card
found. Use just a simple foreach
for this, like for example:
string SomeFunc(IEnumerable<Card> cards)
{
foreach(Card in cards)
{
if(c.GetFaceValue().ToString() == card) {
return "Your Card has been located";
}
}
Upvotes: 0
Reputation: 723388
You're currently trying to return a message from the anonymous function and not your calling code; that won't work as the anonymous function is an Action<T>
, which can't return anything.
Do you just want to see if any element in cards
matches card
and return the message if so?
Use .Any()
instead of .ForEach()
:
if (cards.Any(c => c.GetFaceValue().ToString() == card))
{
return "Your Card has been located";
}
Upvotes: 4
Reputation: 148514
the ForEach has a void - you cant return a value.
Action is a delegate shortcut for
public delegate void Action<in T>(
T obj
)
notice the void here.
http://msdn.microsoft.com/en-us/library/bwabdf9z.aspx
public void ForEach(
Action<T> action
)
Upvotes: 0