Tuesday, January 17, 2012

Iterating Over a Tuple in .NET

While I'm thinking about tuples and .NET I figured I should take the subject one step further. One of the things that I referenced in my previous post (see this) was that you can't iterate over a tuple in .NET. System.Tuple doesn't implement IEnumerable. Some people might ask why you would want to? I'll be honest I haven't given it much thought. At this point it's all academic as I haven't encountered a problem that screams for a tuple let alone the ability to iterate over it. But let's say you have and you want to iterate over the values of a tuple.

Well you can't. Not by default anyway. Remember, no IEnumerable. Oh bother, what to do?

CREATE AN EXTENSION METHOD!

Now I haven't spent too much time on this, and there might be a better way (please enlighten me) but I simply created an extension method that converts a tuple to a generic list of "dynamic" objects. Why? Well a tuple can be composed of various data types so I figured that "dynamic" was a safe bet.

So without further ado, here is my extension method (multiple overloads to account for all available signatures of System.Tuple).

using System;
using System.Collections.Generic;

 namespace Tombatron.Sugar.Extensions
 {
   public static class TupleExtensions
   {
     public static List<dynamic> ToList<T1>(this Tuple<T1> targetuple)
     {
       return BreakTupleApart(targetuple);
     }

     public static List<dynamic> ToList<T1, T2>(this Tuple<T1, T2> targetuple)
     {
       return BreakTupleApart(targetuple);
     }

     public static List<dynamic> ToList<T1, T2, T3>(this Tuple<T1, T2, T3> targetuple)
     {
       return BreakTupleApart(targetuple);
     }

     public static List<dynamic> ToList<T1, T2, T3, T4>(this Tuple<T1, T2, T3, T4> targetuple)
     {
       return BreakTupleApart(targetuple);
     }

     public static List<dynamic> ToList<T1, T2, T3, T4, T5>(this Tuple<T1, T2, T3, T4, T5> targetuple)
     {
       return BreakTupleApart(targetuple);
     }

Read more: tombatron.com
QR: Iterating-Over-a-Tuple-in-NET

Posted via email from Jasper-Net