C# ValueTuple of any size

可紊 提交于 2020-07-06 18:43:50

问题


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];
        }
    }
}

回答1:


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;
}


来源:https://stackoverflow.com/questions/56413583/c-sharp-valuetuple-of-any-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!