I wish to whether it is possible to modify this program by using foreach instead for loop
using System;
public class ParallelArrays
{
public static void Main()
{
int[] validValues = { 101, 108, 201, 213, 266, 304, 311, 409, 411, 412 };
double[] prices = { 0.89, 1.23, 3.50, 0.69, 5.79, 3.19, 0.99, 0.89, 1.26, 8.00 };
//parallel array
int itemOrdered = 311;
for (int i = 0; i < validValues.Length; ++i)
{
if (itemOrdered == validValues[i]) //order doesn't matter
{
Console.WriteLine(prices[i]);
}
}
Console.ReadKey();
}
}
/*
0.99
*/
Loading
VulpesPosted Dec 10, 2011, 4:15 PM
Here's the two array case using tuples:
You can also create a custom class which has the merit that you can use sensible names (not just Item1, Item2) for the parallel elements. However, if you're not too bothered about that, then tuples are more convenient.
Sam HobbsPosted Dec 10, 2011, 3:49 PM
If the data exists in the manner you show in which the position of the price corresponds to the validValue then you can use a List
double[] prices = { 0.89, 1.23, 3.50, 0.69, 5.79, 3.19, 0.99, 0.89, 1.26, 8.00 };
List validValuesList = new List(validValues);
//
int itemOrdered = 311;
int i = validValuesList.BinarySearch(itemOrdered);
if (i >= 0)
Console.WriteLine(prices[i]);
An alternative is a Dictionary or SortedList. I am not sure this would satisfy your requirements but it appears to and if it does then this is what an experienced developer would use.
PricesByValues[101] = 0.89;
PricesByValues[108] = 1.23;
PricesByValues[201] = 3.50;
PricesByValues[213] = 0.69;
PricesByValues[266] = 5.79;
PricesByValues[304] = 3.19;
PricesByValues[311] = 0.99;
PricesByValues[409] = 0.89;
PricesByValues[411] = 1.26;
PricesByValues[412] = 8.00;
int itemOrdered = 311;
double d;
if (PricesByValues.TryGetValue(itemOrdered, out d))
Console.WriteLine(d);
Posted Dec 10, 2011, 2:27 PM
VulpesPosted Dec 10, 2011, 1:51 PM