Can I use a collection initializer for Dictionary entries?

前端 未结 7 1331
猫巷女王i
猫巷女王i 2020-12-09 14:19

I want to use a collection initializer for the next bit of code:

public Dictionary GetNames()
{
    Dictionary names =          


        
相关标签:
7条回答
  • 2020-12-09 14:45

    If you're looking for slightly less verbose syntax you can create a subclass of Dictionary<string, object> (or whatever your type is) like this :

    public class DebugKeyValueDict : Dictionary<string, object>
    {
    
    }
    

    Then just initialize like this

    var debugValues = new DebugKeyValueDict
                      {
                           { "Billing Address", billingAddress }, 
                           { "CC Last 4", card.GetLast4Digits() },
                           { "Response.Success", updateResponse.Success }
                      });
    

    Which is equivalent to

    var debugValues = new Dictionary<string, object>
                      {
                           { "Billing Address", billingAddress }, 
                           { "CC Last 4", card.GetLast4Digits() },
                           { "Response.Success", updateResponse.Success }
                      });
    

    The benefit being you get all the compile type stuff you might want such as being able to say

    is DebugKeyValueDict instead of is IDictionary<string, object>

    or changing the types of the key or value at a later date. If you're doing something like this within a razor cshtml page it is a lot nicer to look at.

    As well as being less verbose you can of course add extra methods to this class for whatever you might want.

    0 讨论(0)
  • 2020-12-09 14:47
    var names = new Dictionary<int, string> {
      { 1, "Adam" },
      { 2, "Bart" },
      { 3, "Charlie" }
    };
    
    0 讨论(0)
  • 2020-12-09 14:48

    The syntax is slightly different:

    Dictionary<int, string> names = new Dictionary<int, string>()
    {
        { 1, "Adam" },
        { 2, "Bart" }
    }
    

    Note that you're effectively adding tuples of values.

    As a sidenote: collection initializers contain arguments which are basically arguments to whatever Add() function that comes in handy with respect to compile-time type of argument. That is, if I have a collection:

    class FooCollection : IEnumerable
    {
        public void Add(int i) ...
    
        public void Add(string s) ...
    
        public void Add(double d) ...
    }
    

    the following code is perfectly legal:

    var foos = new FooCollection() { 1, 2, 3.14, "Hello, world!" };
    
    0 讨论(0)
  • 2020-12-09 14:52

    In the following code example, a Dictionary<TKey, TValue> is initialized with instances of type StudentName.

      Dictionary<int, StudentName> students = new Dictionary<int, StudentName>()
      {
          { 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}},
          { 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317}},
          { 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198}}
      };
    

    from msdn

    0 讨论(0)
  • 2020-12-09 14:58

    The question is tagged c#-3.0, but for completeness I'll mention the new syntax available with C# 6 in case you are using Visual Studio 2015 (or Mono 4.0):

    var dictionary = new Dictionary<int, string>
    {
       [1] = "Adam",
       [2] = "Bart",
       [3] = "Charlie"
    };
    

    Note: the old syntax mentioned in other answers still works though, if you like that better. Again, for completeness, here is the old syntax:

    var dictionary = new Dictionary<int, string>
    {
       { 1, "Adam" },
       { 2, "Bart" },
       { 3, "Charlie" }
    };
    

    One other kind of cool thing to note is that with either syntax you can leave the last comma if you like, which makes it easier to copy/paste additional lines. For example, the following compiles just fine:

    var dictionary = new Dictionary<int, string>
    {
       [1] = "Adam",
       [2] = "Bart",
       [3] = "Charlie",
    };
    
    0 讨论(0)
  • 2020-12-09 14:59
    return new Dictionary<int, string>
    { 
       { 1, "Adam" },
       { 2, "Bart" },
       ...
    
    0 讨论(0)
提交回复
热议问题