1

I have 2 array

string[] Namesvalues = Names.Split(',');
string[] TotalValues = Total.Split(',');

Above both arrays have exactly equal values.what i want to do is to iterate above two arrays in parallel and want to get one by one value from both arrays.

Can any one tell me how can i do that??

Max
  • 12,622
  • 16
  • 73
  • 101
adward
  • 289
  • 6
  • 19
  • "both arrays have exactly equal values", I assume you are saying they have the same number of elements? – Dirk Jun 30 '14 at 06:54
  • @Dirk yeah right both have the same number of elements – adward Jun 30 '14 at 06:55
  • Wouldn't it be easier to use a normal for loop and use the iterator to access the arrays. After checking the lengths are the same. Assuming you want to compare of use them. – Simeon Pilgrim Jun 30 '14 at 06:56
  • You can use typical for loop instead of foreach... any reason you are looking for foreach solution or you just want to iterate? – Adil Jun 30 '14 at 06:56
  • [Duplicate](http://stackoverflow.com/questions/1955766/iterate-two-lists-or-arrays-with-one-foreach-statement-in-c-sharp?rq=1) provides answer to your exact question. Note that it may be better to create custom class (Name,Total) instead of 2 separate arrays or simply use `for` loop. – Alexei Levenkov Jun 30 '14 at 06:57

2 Answers2

6

You could simply use a for-loop:

for(int i = 0; i < NamesValues.Length; i++)
{
    string name = NamesValues[i];
    string totalValue = TotalValues[i];
}

If the length is different you could use ElementAtOrDefault:

for(int i = 0; i < Math.Max(NamesValues.Length, TotalValues.Length) ; i++)
{
    string name = NamesValues.ElementAtOrDefault(i);
    string totalValue = TotalValues.ElementAtOrDefault(i);
}

You also could use Enumerable.Zip to create an anonymous type with both values:

var namesAndValues = NamesValues.Zip(TotalValues, 
    (n, tv) => new { Name = n, TotalValue = tv });
foreach(var nv in namesAndValues)
{
    Console.WriteLine("Name: {0} Value: {1}", nv.Name + nv.TotalValue);
}

Note that the second approach using a for-loop and ElementAtOrDefault is different to to the Enumerable.Zip approach.

  • The former iterates both arrays completely and ElementAtOrDefault returns null for the value of the smaller array if there is no element at that index.
  • The latter Zip combines elements only until it reaches the end of one of the sequences.

So when you use Math.Min instead of Math.Max in the for-loop you get a similar behaviour, but then you should use the first approach anyway since there's no need for ElementAtOrDefault.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0
//exactly equal length
for (int i = 0; i < Namesvalues.Length; i++)
{
    var name = Namesvalues[i];
    var total = TotalValues[i];
}
Robert Fricke
  • 3,637
  • 21
  • 34