Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Representing Typed N-tuples in C#

List<struct {string, string, double} > L = new List<struct {string, string, double}>;
L.Add({"hi", "mom", 5.0});

What is the nicest way to get this functionality in C#? I want to define a strongly-typed tuple on the fly (for use in a local function), save a bunch of them in a list, do some processing and return a result, never to touch the list again.

I don't actually care about the strong typing, but a List of vars doesn't work. Do I want a list of objects? Is that the closest I can get?

Defining structs or classes for temporary data structures seems verbose and pedantic to me.

like image 666
John Shedletsky Avatar asked Apr 05 '11 21:04

John Shedletsky


People also ask

What is N tuple notation?

An n-tuple is a sequence (or ordered list) of n elements, where n is a non-negative integer. There is only one 0-tuple, referred to as the empty tuple. An n-tuple is defined inductively using the construction of an ordered pair.

Can a tuple have 3 items?

In C#, a 3-tuple is a tuple that contains three elements and it is also known as triple. You can create a 3-tuple using two different ways: Using Tuple<T1,T2,T3>(T1, T2, T3) Constructor.

Is there tuple in C?

Tuples in C++A tuple is an object that can hold a number of elements. The elements can be of different data types.

Is tuple value type?

Tuple types are value types; tuple elements are public fields. That makes tuples mutable value types.


2 Answers

The best way to represent this in C# is to use the Tuple type

var l = new List<Tuple<string, string, double>>();
l.Add(Tuple.Create("hi", "mom", 42.0));

There's no explicit language support for tuples but as you can see the API isn't too wordy

like image 171
JaredPar Avatar answered Nov 27 '22 12:11

JaredPar


var arr = new[] { Tuple.Create("hi","mom", 5.0) };

is the easiest; this is actually an array, but a list is easy enough too - perhaps .ToList() if you feel lazy.

Personally, in this scenario I'd use an anon-type:

var arr = new[] { new { Text = "hi", Name = "mom", Value = 5.0 } };

Very similar, except the member-names are more meaningful.

like image 23
Marc Gravell Avatar answered Nov 27 '22 11:11

Marc Gravell