简体   繁体   中英

C# ValueTuple of any size

Is it possible to write a C# method that accepts a value tuple with any number of items of the same type and converts them into a list?

Edit 2/6/2019 I accepted the Provided answer as the correct one. I wanted to also provide a solution that uses a base class that is not an interface, becuase I am trying to write a conversion operator and user defined conversions from an interface are not allowed.

public static class TupleExtensions
{
    public static IEnumerable<object> Enumerate(this ValueType tpl)
    {
        var ivt = tpl as ITuple;
        if (ivt == null) yield break;

        for (int i = 0; i < ivt.Length; i++)
        {
            yield return ivt[i];
        }
    }
}

You can use the fact that ValueTuples implement the ITuple interface.

The only issue is that tuple elements can be of arbitrary type, so the list must accept any kind of type.

public List<object> TupleToList(ITuple tuple)
{
  var result = new List<object>(tuple.Length);
  for (int i = 0; i < tuple.Length; i++)
  {
    result.Add(tuple[i]);
  }
  return result;
}

This also works as an extension method:

public static class ValueTupleExtensions
{
  public static List<object> ToList(this ITuple tuple)
  {
    var result = new List<object>(tuple.Length);
    for (int i = 0; i < tuple.Length; i++)
    {
      result.Add(tuple[i]);
    }
    return result;
  }
}

This way it is possible to write var list = (123, "Text").ToList(); .

Edit 2020-06-18: If every element of the tuple is of the same type it's possible to create list with the proper element type:

public List<T> TupleToList<T>(ITuple tuple)
{
  var result = new List<T>(tuple.Length);
  for (int i = 0; i < tuple.Length; i++)
  {
    result.Add((T)tuple[i]);
  }
  return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM