I have a nested loop which is checking if any Currency
of Wallet[]
matches any Currency
in Currency[] UtilityTokens
.
Upon determining that indeed one of the wallets contains a utility token, I want to break my nested loop as soon as possible to move on.
My current code is the following:
bool walletContainsUtilityToken = false;
for(int i = 0; i < Wallets.Length; i )
{
foreach (Currency ut in ExchangeFunctions.UtilityTokens)
{
if (Wallets[i].Currency.Equals(ut))
{
walletContainsUtilityToken = true;
break;
}
}
if (walletContainsUtilityToken)
{
break;
}
}
Is this the apropriate way to break nested loops? Is there a different, more efficient way of doing things?
CodePudding user response:
We can get this down to a one-liner, and it will do the early exit you want:
bool walletContainsUtilityToken = Wallets.Any(w => ExchangeFunctions.UtilityTokens.Any( ut => ut == w.Currency));
This one might be easier to understand (no nesting, only one -shorter- lambda):
bool walletContainsUtilityToken = Wallets.Select(w => w.Currency).Intersect(ExchangeFunctions.UtilityTokens).Any();
Taking the second option, for clarity I'd actually write it like this:
bool walletContainsUtilityToken = Wallets.
Select(w => w.Currency).
Intersect(ExchangeFunctions.UtilityTokens).
Any();
If you really want to continue using the full loop, I'd add a check to the loop conditions like so:
bool walletContainsUtilityToken = false;
for(int i = 0; i < Wallets.Length && !walletContainsUtilityToken; i )
{
foreach (Currency ut in ExchangeFunctions.UtilityTokens)
{
if (Wallets[i].Currency.Equals(ut))
{
walletContainsUtilityToken = true;
break;
}
}
}
Finally, if these lists are large you could significantly improve performance by pre-arranging them into data structures for faster lookup (ie: a Dictionary, or even something that would support a binary search). But this is only a win if the lists are large enough.
CodePudding user response:
May be you can use goto
.
example:
int val = 2;
for(int i = 0; i <4;i )
{
for (int j =0;j<4; j )
{
if (val == i)
goto LoopsFinished;
}
}
LoopsFinished:
val = 0;
CodePudding user response:
Your code is perfectly fine, if you want a one-liner here is a Linq alternative.
bool walletContainsUtilityToken = Wallets.Any(w => ExchangeFunctions.UtilityTokens.Any(ut => w.Currency.Equals(ut)));