How do you use object initializers for a list of key value pairs?

前端 未结 5 656
南方客
南方客 2020-12-29 17:46

I can\'t figure out the syntax to do inline collection initialization for:

var a = new List>();
相关标签:
5条回答
  • 2020-12-29 18:32

    Another alternative that doesn't require making a subclass:

    List<KeyValuePair<String, String>> list = new Dictionary<String, String>
        {
            {"key1", "value1"},
            {"key2", "value2"},
        }.ToList();
    

    As mentioned in the comments: drawbacks with this method include possible loss of ordering and inability to add duplicate keys.

    0 讨论(0)
  • 2020-12-29 18:33

    Pretty straightforward:

    var a = new List<KeyValuePair<string, string>>()
    {
        new KeyValuePair<string, string>("A","B"),
        new KeyValuePair<string, string>("A","B"),
        new KeyValuePair<string, string>("A","B"),
    };
    

    Note that you can leave the trailing comma after the last element (probably because .net creators wanted to make automatic code-generation easier), or remove the () brackets of the list contructor and the code still compiles.

    0 讨论(0)
  • 2020-12-29 18:34

    Note that the dictionary collection initialization { { key1, value1 }, { key2, value2 } } depends on the Dictionary's Add(TKey, TValue) method. You can't use this syntax with the list because it lacks that method, but you could make a subclass with the method:

    public class KeyValueList<TKey, TValue> : List<KeyValuePair<TKey, TValue>>
    {
        public void Add(TKey key, TValue value)
        {
            Add(new KeyValuePair<TKey, TValue>(key, value));
        }
    }
    
    public class Program
    {
        public static void Main()
        {
            var list = new KeyValueList<string, string>
                       {
                           { "key1", "value1" },
                           { "key2", "value2" },
                           { "key3", "value3" },
                       };
        }
    }
    
    0 讨论(0)
  • 2020-12-29 18:47

    Any initialization is done by object(params_if_exist) { any public member or instance};

    f.e. var list = new List<int> {1,2,3};

    var bw = new BackgroundWorker() {WorkerSupportsCancellation = true};

    0 讨论(0)
  • 2020-12-29 18:50

    Since collection initializers (C# 6.0) have not been mentioned here:

    Implementation

    public static class InitializerExtensions
    {
       public static void Add<T1, T2>(this ICollection<KeyValuePair<T1, T2>> target, T1 item1, T2 item2)
       {
           if (target == null)
                throw new ArgumentNullException(nameof(target));
    
            target.Add(new KeyValuePair<T1, T2>(item1, item2));
        }
    }
    

    Usage

    var list = new List<KeyValuePair<string, string>> { {"ele1item1", "ele1item2"}, { "ele2item1", "ele2item2" } };
    

    How to make it work

    Just include the right using statements in your file so that InitializerExtensions is available (meaning you could call InitializerExtensions.Add explicitly) and the special collection initializer syntax will become available if you are using VS 2015 or higher.

    0 讨论(0)
提交回复
热议问题