I want to create several short (ordered) lists of pairs of strings, and have a neat literal representation in code. Is there a nice way to do this? Best I could come up with is
using Pairs = System.Collections.Specialized.OrderedDictionary;
...
var z = new Pairs()
{
{ "a", "b" },
{ "c", "d" }
};
but the lack of type safety is a bit horrible. There doesn't seem to be a generic ordered dictionary.
What other classes have literal initializer syntax? Is it possible to define your own initializer syntax for a class?
An n
-by-2 array allows this initializer syntax:
string[,] z = { { "a", "b" }, { "c", "d" }, { "z", "w" }, };
In this case dimensions are 3-by-2.
If you prefer an array of arrays, string[][]
, the syntax is just a bit more clumpsy. Some rows could accidentally (or intentionally) have a different length than the others ("jagged" array). An array of arrays might be easier to order using Array.Sort
on the "outer" array, with some IComparer<string[]>
or Comparison<string[]>
.
Otherwise, use SortedDictionary<string, string>
or SortedList<string, string>
as already suggested in a comment by spender
:
var z = new SortedDictionary<string, string> { { "a", "b" }, { "c", "d" }, { "z", "w" }, };
Any type, including user-defined types, that has an (accessible and non-static) Add
method which takes in two strings, will allow this sort of collection initializer. For example:
var z = new YourType { { "a", "b" }, { "c", "d" }, { "z", "w" }, };
will be roughly equivalent to:
YourType z;
{
var temp = new YourType();
temp.Add("a", "b");
temp.Add("c", "d");
temp.Add("z", "w");
z = temp;
}
// use variable z here
Use the Tuple
class - it abstracts nicely over a pair.
Something like:
new List<Tuple<string, string>>()
{
Tuple.Create("a", "b"),
Tuple.Create("c", "d"),
};
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