Easiest way to list string strings literally in C #?

I want to create some short (ordered) lists of line pairs and have a pure literal representation in the code. Is there a good way to do this? The best I could come up with is

using Pairs = System.Collections.Specialized.OrderedDictionary; ... var z = new Pairs() { { "a", "b" }, { "c", "d" } }; 

but type insecurity is a little awful. It seems that there is no common ordered dictionary.

What other classes have literal initialization syntax? Can I define my own initializer syntax for a class?

+4
source share
3 answers

The n -by-2 array allows initializer syntax:

 string[,] z = { { "a", "b" }, { "c", "d" }, { "z", "w" }, }; 

In this case, the dimensions are 3-on-2.

If you prefer an array of arrays, string[][] , the syntax will be a little more clumpsy. Some strings may randomly (or intentionally) have different lengths than others ("jagged" array). An array of arrays may be easier to order using Array.Sort in an "external" array, with some IComparer<string[]> or Comparison<string[]> .

Otherwise, use SortedDictionary<string, string> or SortedList<string, string> , as was already suggested in the comment from 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 that accepts two strings will allow this type of collection initializer to be used. For instance:

 var z = new YourType { { "a", "b" }, { "c", "d" }, { "z", "w" }, }; 

would 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 
+5
source

Use the Tuple class - it perfectly abstracts over the pair. Sort of:

 new List<Tuple<string, string>>() { Tuple.Create("a", "b"), Tuple.Create("c", "d"), }; 
+5
source

There is no common OrderedDictionary, but there is a common SortedDictionary . Use this instead.

0
source

Source: https://habr.com/ru/post/1485015/


All Articles