views:

130

answers:

3

Hi all,

C# newbie working off some tutorials. Is there a way to run an identical command on every object in an array?

Here is my current (working) code:

     Guys[0].Cash += Guys[0].MyGuess.PayOut(WinnerNumber);
     Guys[1].Cash += Guys[1].MyGuess.PayOut(WinnerNumber);
     Guys[2].Cash += Guys[2].MyGuess.PayOut(WinnerNumber);

I'm looking for something that will do this:

     Guys[X].Cash += Guys[X].MyGuess.PayOut(WinnerNumber);

X = is first number on first runthrough, then 2nd number on 2nd runthrough, etc.

+1  A: 

You can do it with a for loop:

for (int i = 0; i < Guys.Length; i++)
{
    Guys[i].Cash += Guys[i].MyGuess.PayOut(WinnderNumber);
}
LukeH
+1  A: 

Its a not-widely documented idiom that you can actually do this with the foreach command, as long as this is a object[] construct:

foreach(GuyObject guy in Guys) {
   guy.Cash += guy.MyGuess.Payout(WinnerNumber);
}

Guess I should add LAMBDA version as well:

Array.ForEach(guys, guy => guy.Cash += guy.MyGuess.Payout(WinnerNumber));
GrayWizardx
Appreciate it! I'm not quite up to LINQ yet, but hopefully I'll have use for that soon. Also appreciate the explanation of foreach.
`ForEach` isn't LINQ. It's a static method on the `Array` class itself.
LukeH
Ugg. Long day, I meant "Lambda version"
GrayWizardx
+8  A: 

You have several options:

Plain old for loop:

for(int i = 0; i < Guys.Length; i++) {
    Guys[i].Cash += Guys[i].MyGuess.PayOut(WinnerNumber);
}

foreach block:

foreach(var guy in Guys) {
    guy.Cash += guy.MyGuess.PayOut(WinnerNumber);
}

Array.ForEach:

Array.ForEach(Guys, g => g.Cash += g.MyGuess.PayOut(WinnerNumber));

These, for me, are in order of preference. Most will prefer the for loop because that is the familiar way of doing something to every item in array in sequence. It's close though between for and foreach.

Jason
Awesome, thanks! The "for loop" method was in my tutorial book, but I was looking for something more like your 2nd two examples. Glad I know what my options are. Thanks much!
Worth noting that `foreach` and `Array.ForEach` will only work if the type is a `class`, not a `struct`. If the type is a `struct` then attempting to use `foreach` will cause a compile-time error, which is fine, but `Array.ForEach` will fail silently at runtime without updating anything.
LukeH