Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to easily initialize a list of Tuples?

I love tuples. They allow you to quickly group relevant information together without having to write a struct or class for it. This is very useful while refactoring very localized code.

Initializing a list of them however seems a bit redundant.

var tupleList = new List<Tuple<int, string>> {     Tuple.Create( 1, "cow" ),     Tuple.Create( 5, "chickens" ),     Tuple.Create( 1, "airplane" ) }; 

Isn't there a better way? I would love a solution along the lines of the Dictionary initializer.

Dictionary<int, string> students = new Dictionary<int, string>() {     { 111, "bleh" },     { 112, "bloeh" },     { 113, "blah" } }; 

Can't we use a similar syntax?

like image 258
Steven Jeuris Avatar asked Nov 03 '11 22:11

Steven Jeuris


People also ask

How do you initialize a list of tuples in Python?

Initialize a TupleYou can initialize an empty tuple by having () with no values in them. You can also initialize an empty tuple by using the tuple function. A tuple with values can be initialized by making a sequence of values separated by commas.

What is list of tuples in Python?

Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage. A tuple is a collection which is ordered and unchangeable. Tuples are written with round brackets.

What are tuples in C#?

The word Tuple means “a data structure which consists of the multiple parts”. So tuple is a data structure which gives you the easiest way to represent a data set which has multiple values that may/may not be related to each other. It introduced in . NET Framework 4.0. In tuple, you can add elements from 1 to 8.


1 Answers

c# 7.0 lets you do this:

  var tupleList = new List<(int, string)>   {       (1, "cow"),       (5, "chickens"),       (1, "airplane")   }; 

If you don't need a List, but just an array, you can do:

  var tupleList = new(int, string)[]   {       (1, "cow"),       (5, "chickens"),       (1, "airplane")   }; 

And if you don't like "Item1" and "Item2", you can do:

  var tupleList = new List<(int Index, string Name)>   {       (1, "cow"),       (5, "chickens"),       (1, "airplane")   }; 

or for an array:

  var tupleList = new (int Index, string Name)[]   {       (1, "cow"),       (5, "chickens"),       (1, "airplane")   }; 

which lets you do: tupleList[0].Index and tupleList[0].Name

Framework 4.6.2 and below

You must install System.ValueTuple from the Nuget Package Manager.

Framework 4.7 and above

It is built into the framework. Do not install System.ValueTuple. In fact, remove it and delete it from the bin directory.

note: In real life, I wouldn't be able to choose between cow, chickens or airplane. I would be really torn.

like image 156
toddmo Avatar answered Oct 08 '22 16:10

toddmo