View Single Post
  #1 (permalink)  
Old August 2nd, 2011, 07:24 PM
esherr01 esherr01 is offline
Authorized User
Points: 130, Level: 2
Points: 130, Level: 2 Points: 130, Level: 2 Points: 130, Level: 2
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2011
Posts: 32
Thanks: 22
Thanked 0 Times in 0 Posts
Default populate an array using LINQ and foreach

Hi:

I am trying to populate an array from a series of fields in a table that come from various records. I am confident that the data is there.

In a method I have the following LINQ statement:

Code:
var HDiffquery = from RoundOfGolf in db.RoundOfGolfs
                       where (RoundOfGolf.Customer_ID == customer &&
                       RoundOfGolf.Player_ID == player)
                       select RoundOfGolf.HDiff;
The idea is that I will have "several" of these HDiffs from my table, but how many? Earlier in the code I have:

Code:
 int recordsReturned = (from RoundOfGolf in db.RoundOfGolfs
                    where (RoundOfGolf.Customer_ID == customer && RoundOfGolf.Player_ID == player)
                    select RoundOfGolf).Count();
Which should give me the number of matching records,so now I do the following:
Code:
 string[] diffs = new string[recordsReturned]; //create string array
to determine the array size needed and now I want to take ALL the mathcing HDiff field values and after converting to a string value assign to the array of correct size

Code:
int i = 0;
foreach (var result in HDiffquery)
      {
         diffs[i] = result.ToString();
      }//end foreach
which is where I think I'm getting myself in trouble by using a foreach statement to theoretically populate the array with all of the HDiffs. I copy the string array into a matching double array as I need to do some mathematics on the array (adding) and that's where I get the error"Index is outside the bounds of the array" when I attempt the following:

Code:
for (i = 0; i < recordsReturned; i++)
         total += realDiffs[i];
My sense is that the foreach statement is incorrectly constructed.

As always,
Cliff
Reply With Quote