How to write an API that accepts a number of anonymous dictionary elements?

I often have to write APIs that include pairs of key values, when I work with this, I usually get a collection object List<KeyValuePair<string,string>>or similar type that allows me to write operations very easily.

The only drawback that I encountered is the addition of several elements to this collection, as a rule, leads to a very noisy block of code, for example

MyDictionary.Put(new KeyValuePair<string, string>("a","1"), 
                 new KeyValuePair<string, string>("b","2"), 
                 new KeyValuePair<string, string>("c","3"))

I would rather be able to do

MyDictionary.Put( {"a","1"},  {"b","2"},  {"c","3"})

Several times I tried to execute and always end up what C # expects exactly as the syntax for this.

+3
source share
4 answers

Collection initializers allow much of this:

var data = new Dictionary<string,string> {
    {"a","1"},
    {"b","2"},
    {"c","3"}
};

- object , ():

new { a = "1", b = "2", c = "3" }

, , ( ..), , . , ( ).

+4

, ...

MyDictionary.Put("a=1", "b=2", "c=3");

- ...

void Put(params string[] nameEqualValues)
{
    foreach (string nameEqualValue in nameEqualValues)
    {
        int iEquals = nameEqualValue.IndexOf('=');
        if (iEquals < 0)
        {
            throw new ApplicationException(...);
        }
        string name = nameEqualValue.Substring(0, iEquals);
        string val = nameEqualValue.Substring(iEquals + 1);

        this.PutNameValue(name, val);
    }
}

, - , , .

, , , , ...

MyDictionary.Put(d + "=" + x, e + "=" + y);
MyDictionary.Put(String.Format("{0}={1}", d, x), ...);

, , "params string []", Put . ( python;)

+1

Require that the parameters fall in pairs and process evens (zero, two, ...) as keys and coefficients as values:

void Put(params string[] items)
{
    if (items.Length % 2 != 0) throw new ArgumentException("Expected even number");

    for (int i = 0; i < items.Length; i += 2)
    {
        this.myDict[items[i]] = items[i+1];
    }
}
+1
source

I can't figure out a very clean way to do this, but one workaround for smaller typing might be this:

public class MyDictionary : List<KeyValuePair<string, string>>
{
    ...

    public void Put(params string[][] p)
    {
        foreach (var a in p)
            Add(new KeyValuePair<string, string>(a[0], a[1]));
    }
}

which can be called as follows:

MyDictionary.Put(new[] {"a", "1"}, new[] {"b", "2"}, new[] {"c", "3"});

But this is a certain memory loss, as well as very inefficient coding.

+1
source

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


All Articles