Tuesday, 5 September 2017

c# - 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.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 students = new Dictionary()
{
{ 111, "bleh" },
{ 112, "bloeh" },
{ 113, "blah" }
};



Can't we use a similar syntax?


Answer



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



  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.


No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...