任意大小的 C# ValueTuple

标签 c# collections tuples

是否可以编写一个 C# 方法来接受具有任意数量的相同类型的值元组并将它们转换为列表?

编辑 2/6/2019 我接受了提供的答案作为正确答案。我还想提供一个使用不是接口(interface)的基类的解决方案,因为我正在尝试编写一个转换运算符,并且不允许从接口(interface)进行用户定义的转换。

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

最佳答案

您可以使用 ValueTuples 实现 ITuple 的事实界面。

唯一的问题是元组元素可以是任意类型,因此列表必须接受任何类型。

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

这也可以作为扩展方法:

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

这样就可以编写 var list = (123, "Text").ToList();

编辑 2020-06-18:如果元组的每个元素都属于同一类型,则可以创建具有适当元素类型的列表:

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

关于任意大小的 C# ValueTuple,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56413583/

相关文章:

c# - 使用C#+MySql数据库使用Web Service的困惑

c# - WPF 工具包数据列可见性绑定(bind)

java - ArrayList 删除与 removeAll

python - 字典中的反向元素

python - 如何将元组列表转换为python中部分元组的列表

c# - 安装/删除 2013 测试版后损坏的 Excel Interop COM 程序集

c# - 登录表单不会关闭

java - 从列表中删除项目或添加构建新列表?

swift - 返回泛型集合的迭代器 - Swift 4.2

c++ - 如何通过标准元组操作正确转发和使用 constexpr 结构的嵌套元组