Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to iterate over tuple items

How to iterate over items in a Tuple, when I dont know at compile-time what are the types the tuple is composed of? I just need an IEnumerable of objects (for serialization).

private static IEnumerable TupleToEnumerable(object tuple)
{
    Type t = tuple.GetType();
    if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Tuple<,>))
    {
        var x = tuple as Tuple<object, object>;
        yield return x.Item1;
        yield return x.Item2;
    }
}
like image 755
tula sacra Avatar asked Apr 11 '17 08:04

tula sacra


People also ask

How do you iterate over a tuple?

We can iterate over tuples using a simple for-loop. We can do common sequence operations on tuples like indexing, slicing, concatenation, multiplication, getting the min, max value and so on.

How do you loop through a tuple of tuples?

Easiest way is to employ two nested for loops. Outer loop fetches each tuple and inner loop traverses each item from the tuple. Inner print() function end=' ' to print all items in a tuple in one line. Another print() introduces new line after each tuple.

Can you iterate through a tuple C++?

A C++ tuple is a container that can store multiple values of multiple types in it. We can access the elements of the tuple using std::get(), but std::get() always takes a constant variable parameter, so we can not simply iterate through it using a loop.

How do you enumerate a list of tuples?

Use the enumerate() function to iterate over a list of tuples, e.g. for index, tup in enumerate(my_list): . The enumerate function returns an object that contains tuples where the first item is the index, and the second is the value.


1 Answers

In .NET Core 2.0+ or .NET Framework 4.7.1+, there are

  • t.Length
  • t[i]

it's from an interface ITuple interface

var data = (123, "abc", 0.983, DateTime.Now);
ITuple iT = data as ITuple;

for(int i=0; i<iT.Length;i++)
  Console.WriteLine(iT[i]);
like image 188
Rm558 Avatar answered Oct 14 '22 05:10

Rm558