简体   繁体   中英

How to create a List of ValueTuple?

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

like this:

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

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 (ie without repeating the property names) by supplying the names for the properties in the tuple creation, ie

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM