How to create a List of ValueTuple?

谁都会走 提交于 2019-11-30 06:35:55

You are looking for a syntax like this:

List<(int, string)> list = new List<(int, string)>();
list.Add((3, "first"));
list.Add((6, "second"));

You can use like that in your case:

List<(int, string)> Method() => 
    new List<(int, string)>
    {
        (3, "first"),
        (6, "second")
    };

You can also name the values before returning:

List<(int Foo, string Bar)> Method() =>
    ...

And you can receive the values while (re)naming them:

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

Sure, you can do this:

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

Just to add to the existing answers, with regards to projecting ValueTuples from existing enumerables and with regards to property naming:

You can still name the tuple properties AND still use var type inferencing (i.e. without repeating the property names) by supplying the names for the properties in the tuple creation, i.e.

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

// Access each item.example and item.descrpt

Similarly, when returning enumerables of tuples from a method, you can name the properties in the method signature, and then you do NOT need to name them again inside the method:

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

This syntax is best applied to c# 6 but can be used in c# 7 as well. Other answers are much more correct because the are tending to use ValueTuple instead of Tuple used here. You can see the differences here for 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"),
   };
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!