如何创建ValueTuple列表?
是否可以在C#7中创建ValueTuple列表?
像这样:
List Method() { return Something; }
您正在寻找这样的语法:
List<(int, string)> list = new List<(int, string)>(); list.Add((3, "test")); list.Add((6, "second"));
在你的情况下你可以这样使用:
List<(int, string)> Method() => new List<(int, string)> { (3, "test"), (6, "second") };
您还可以在返回之前命名值:
List<(int Foo, string Bar)> Method() => ...
并且您可以在(重新)命名它们时接收值:
List<(int MyInteger, string MyString)> result = Method(); var firstTuple = result.First(); int i = firstTuple.MyInteger; string s = firstTuple.MyString;
当然,你可以这样做:
List<(int example, string descrpt)> Method() => new List { (2, "x") }; var data = Method(); Console.WriteLine(data.First().example); Console.WriteLine(data.First().descrpt);
此语法最适用于c# 6
但也可以在c# 7
中使用。 其他答案更正确,因为它们倾向于使用ValueTuple
而不是此处使用的Tuple
。 您可以在这里看到ValueTuple
的差异
List> Method() { return new List> { new Tuple(2, "abc"), new Tuple(2, "abce"), new Tuple(2, "abcd"), }; }