Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; } 
like image 728
ArthNRick Avatar asked May 29 '17 21:05

ArthNRick


People also ask

How do you create a ValueTuple?

You can create a pair value tuple by using ValueTuple <T1, T2>(T1, T2) constructor. It initializes a new instance of the ValueTuple <T1, T2> struct. But when you create a value tuple using this constructor, then you have to specify the type of the element stored in the value tuple.

How do you initialize a list of tuples?

Initialize a List of Tuples With the () Notation in C# The (x, y) notation in C# specifies a tuple with x and y values. Instead of the Tuple. Create() function, we can also use the () notation inside the list constructor to initialize a list of tuples.

What is a ValueTuple?

ValueTuple is a structure introduced in C# 7.0 which represents the value type Tuple. It is already included in . NET Framework 4.7 or higher version. It allows you to store a data set which contains multiple values that may or may not be related to each other.

Is tuple a value type C#?

Tuple types are value types; tuple elements are public fields. That makes tuples mutable value types. The tuples feature requires the System.


1 Answers

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; 
like image 197
Guilherme Avatar answered Oct 09 '22 13:10

Guilherme