How to create a List of ValueTuple?

2020-02-25 04:23发布

问题:

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

like this:

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

回答1:

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;


回答2:

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


回答3:

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


回答4:

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"),
   };
}