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.
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.
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.
Tuples in C++A tuple is an object that can hold a number of elements. The elements can be of different data types.
Tuple types are value types; tuple elements are public fields. That makes tuples mutable value types.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With