How to create a List of ValueTuple?
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);
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;
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