如何创建一个ValueTuple列表?

43

在 C# 7 中,是否可以创建一个 ValueTuple 的列表?

类似这样:

List<(int example, string descrpt)> Method()
{
    return Something;
}

33
为什么不试试? - Camilo Terevinto
5
我几乎想要点个踩,因为这确实是返回具名元组列表所需的语法。为什么会有这个问题呢? - Panagiotis Kanavos
5
我想这个问题不是关于方法的返回类型,而是关于缺少的Something - quetzalcoatl
4个回答

110

你正在寻找类似于这样的语法:

List<(int, string)> list = new List<(int, string)>();
list.Add((3, "first"));
list.Add((6, "second"));
你可以在你的情况下这样使用:
List<(int, string)> Method() => 
    new List<(int, string)>
    {
        (3, "first"),
        (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;

2
最好在方法定义中命名字段。 - Panagiotis Kanavos

13

当然,你可以这样做:

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

5

除了现有的答案之外,就投影现有枚举中的ValueTuples和属性命名而言:

您仍然可以为元组属性命名,并且仍然可以使用var类型推断(即不重复属性名称)通过在元组创建中提供属性名称,如下所示:

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

// Access each item.example and item.descrpt

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

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

0

这种语法最适用于 c# 6,但也可以在 c# 7 中使用。其他答案更正确,因为它们倾向于使用 ValueTuple 而不是此处使用的 Tuple。您可以在 这里 查看 ValueTuple 的区别。

List<Tuple<int, string>> Method()
{
   return new List<Tuple<int, string>>
   {
       new Tuple<int, string>(2, "abc"),
       new Tuple<int, string>(2, "abce"),
       new Tuple<int, string>(2, "abcd"),
   };
}

List<(int, string)> Method()
{
   return new List<(int, string)>
   {
       (2, "abc"),
       (2, "abce"),
       (2, "abcd"),
   };
}

2
No need to use "Tuple" at all - Camilo Terevinto
1
我肯定更喜欢这种语法,比其他语法更易读和清晰。 - Gusman
2
点赞。这是 C# 6 及以下版本的正确语法。 - Guilherme
7
因为这个答案使用了Tuple而不是ValueTuple,所以被踩了。 - David Arno
7
Tuple 和 ValueTuple 在内存使用和性能方面有显著的差异。当人们询问 C# 7 和元组时,他们指的不是旧的 Tuples。Tuple 创建在堆上并需要进行垃圾回收,而 ValueTuple 则创建在栈上。 - Panagiotis Kanavos
显示剩余7条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接