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
.