如何创建ValueTuple列表?

Art*_*ick 23 c# c#-7.0 valuetuple

是否可以在C#7中创建ValueTuple列表?

像这样:

List<(int example, string descrpt)> Method()
{
    return Something;
}
Run Code Online (Sandbox Code Playgroud)

Gui*_*rme 73

您正在寻找这样的语法:

List<(int, string)> list = new List<(int, string)>();
list.Add((3, "first"));
list.Add((6, "second"));
Run Code Online (Sandbox Code Playgroud)

在你的情况下你可以这样使用:

List<(int, string)> Method() => 
    new List<(int, string)>
    {
        (3, "first"),
        (6, "second")
    };
Run Code Online (Sandbox Code Playgroud)

您还可以在返回之前命名值:

List<(int Foo, string Bar)> Method() =>
    ...
Run Code Online (Sandbox Code Playgroud)

并且您可以在(重新)命名它们时接收值:

List<(int MyInteger, string MyString)> result = Method();
var firstTuple = result.First();
int i = firstTuple.MyInteger;
string s = firstTuple.MyString;
Run Code Online (Sandbox Code Playgroud)

  • 最好在方法定义中命名字段。 (2认同)

SO *_*ood 9

当然,你可以这样做:

List<(int example, string descrpt)> Method() => new List<(int, string)> { (2, "x") };

var data = Method();
Console.WriteLine(data.First().example);
Console.WriteLine(data.First().descrpt);
Run Code Online (Sandbox Code Playgroud)


Stu*_*tLC 5

只是添加到现有答案中,关于ValueTuples从现有可枚举项进行投影以及关于属性命名:

您仍然可以var通过在元组创建中提供属性的名称来命名元组属性并仍然使用类型推断(即不重复属性名称),即

var list = Enumerable.Range(0, 10)
    .Select(i => (example: i, descrpt: $"{i}"))
    .ToList();

// Access each item.example and item.descrpt
Run Code Online (Sandbox Code Playgroud)

类似地,当从方法返回元组的枚举时,您可以在方法签名中命名属性,然后您不需要在方法内再次命名它们:

public IList<(int example, string descrpt)> ReturnTuples()
{
   return Enumerable.Range(0, 10)
        .Select(i => (i, $"{i}"))
        .ToList();
}

var list = ReturnTuples();
// Again, access each item.example and item.descrpt
Run Code Online (Sandbox Code Playgroud)