snippetcsharpCritical
How to easily initialize a list of Tuples?
Viewed 0 times
howinitializetupleslisteasily
Problem
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.
Isn't there a better way? I would love a solution along the lines of the Dictionary initializer.
Can't we use a similar syntax?
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?
Solution
c# 7.0 lets you do this:
If you don't need a
And if you don't like "Item1" and "Item2", you can do:
or for an array:
which lets you do:
Framework 4.6.2 and below
You must install
Framework 4.7 and above
It is built into the framework. Do not install
note: In real life, I wouldn't be able to choose between cow, chickens or airplane. I would be really torn.
var tupleList = new List
{
(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
{
(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].NameFramework 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.
Code Snippets
var tupleList = new List<(int, string)>
{
(1, "cow"),
(5, "chickens"),
(1, "airplane")
};var tupleList = new(int, string)[]
{
(1, "cow"),
(5, "chickens"),
(1, "airplane")
};var tupleList = new List<(int Index, string Name)>
{
(1, "cow"),
(5, "chickens"),
(1, "airplane")
};var tupleList = new (int Index, string Name)[]
{
(1, "cow"),
(5, "chickens"),
(1, "airplane")
};Context
Stack Overflow Q#8002455, score: 528
Revisions (0)
No revisions yet.