Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over items in Tuple

I have this method with three loops:

    public void Print(Tuple<List<DateTime>, List<double>, List<string>> dataToPrint)
    {
        foreach (var item in dataToPrint.Item1)
        {
            Console.WriteLine(item);
        }
        foreach (var item in dataToPrint.Item2)
        {
            Console.WriteLine(item);
        }
        foreach (var item in dataToPrint.Item3)
        {
            Console.WriteLine(item);
        }
    }

Is it possible to use only one loop to print all the items with contents of the Lists on the screen?

like image 729
Chris Avatar asked Nov 09 '17 08:11

Chris


Video Answer


1 Answers

You can, of course, concat all lists into one sequence of object or string items, but this concatenation will not make your code more readable. But you can create simple extension method which dumps content of any sequence to the console:

public static void Dump<T>(this IEnumerable<T> source)
{
    foreach(var item in source)
       Console.WriteLine(item);
}

And your code will look like (no loops at all):

public void Print(Tuple<List<DateTime>, List<double>, List<string>> dataToPrint)
{
    dataToPrint.Item1.Dump();
    dataToPrint.Item2.Dump();
    dataToPrint.Item3.Dump();
}

I would also use named parameters, custom type or value tuple to pass these three values to the method.

like image 147
Sergey Berezovskiy Avatar answered Sep 20 '22 18:09

Sergey Berezovskiy