How to create a List of ValueTuple?

Viewed 42496

Is it possible to create a list of ValueTuple in C# 7?

like this:

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

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
Related