Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to represent a list of string pairs literally in c#?

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?

like image 989
Rob Avatar asked Jun 07 '13 10:06

Rob


2 Answers

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
like image 65
Jeppe Stig Nielsen Avatar answered Sep 22 '22 19:09

Jeppe Stig Nielsen


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"),                    
            };
like image 41
aquaraga Avatar answered Sep 22 '22 19:09

aquaraga