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;
}
}
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.
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.
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.
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.
In .NET Core 2.0+ or .NET Framework 4.7.1+, there are
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With