0

I have two lists as

foreach (var a in _teams)
{
    Console.WriteLine(a);
}

foreach (var b in _wins)
{
    Console.WriteLine(b);
}

Each list have same number of values. Right now i am printing each values separtely but how can i print each value of a or b together .

_teams list return Australia, England , USA _wins list return 5,6,7

I want to print like that Australia 5, England 6, USA 7

Updated * i am creating xml nodes so basically i dont want to print it together. I want values like Australia than 5 than England than 6 so on and i will create xml nodes like

<Team>Australia</Team>
<Win>5</Win>
<Team>England </Team>
<Win>6</Win>

...so on

6 Answers6

0

How about this:

for(i = 0; i < _teams.Length; i++)
{
    Console.Write(_teams[i] + " ");
    Console.Write(_wins[i]);
    if(i < _teams.Length - 1)
        Console.Write(",");
}
rcs
  • 6,713
  • 12
  • 53
  • 75
0

I would suggest looking into the zip function on IEnumerable. Something like this:

var lst1 = new List<string>(){"One", "Two","Three"};
var lst2 = new List<string>(){"A", "B","C"};
var combined = lst1.Zip(lst2, (fst,snd) => {return fst + ":" + snd;});
foreach (var item in combined)
{
    Console.WriteLine (item);
}

Zip will take two seperate lists and allow you to build a single view into both.

Gary.S
  • 7,076
  • 1
  • 26
  • 36
0

Try this:

foreach (var a in _teams.Zip(_wins, (t, w) => new { t, w }))
{
    Console.WriteLine(a.t + " " + a.w);
}
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
0

you can use below menioned code

        List<string> _terms = new List<string>();
        List<string> _wins = new List<string>();
        _terms.Add("Australia");
        _wins.Add("5");
        using (var e1 = _terms.GetEnumerator())
        using (var e2 = _wins.GetEnumerator())
        {
            while (e1.MoveNext() && e2.MoveNext())
            {
                var item1 = e1.Current;
                var item2 = e2.Current;

                // use item1 and item2
            }
        }
Dhaval Patel
  • 7,471
  • 6
  • 37
  • 70
0

You could use a for loop...

for (int i = 0; i < teams.Count; i++)
{
    Console.WriteLine(_teams[i]);
    Console.WriteLine(_wins[i]);
}

... but Dictionary is a better solution:

Dictionary<string, int> _teams = new Dictionary<string, int>();
_teams.Add("Australia", 5);
_teams.Add("England", 6);
...
foreach( KeyValuePair<string, int> kvp in _teams )
{
    Console.WriteLine("{0} {1}", kvp.Key, kvp.Value);
}

MSDN Dictionary

insilenzio
  • 918
  • 1
  • 9
  • 23
0

Try this:

_teams.ForEach(x => Console.WriteLine(x +" " + _wins[_teams.IndexOf(x)]));

We use the IndexOf method to get index of the current string from _teams, and get the element at that index of _wins.

However, if this is a 1-to-1 map between team and it's wins, a Dictionary would be my preferred data structure.

shree.pat18
  • 21,449
  • 3
  • 43
  • 63