0

how to assign this read only variable in constructor.

private readonly Dictionary<string, Dictionary<string, int>> nCount = new Dictionary<string, Dictionary<string, int>>();

Want to initialize this variable in constructor:

  public mclass() {

        nCount = new Dictionary<string, Dictionary<string, int>>();

    }

on the initializing time need to add a stringComparer to inner Dictornary

Amit Arya
  • 13
  • 6
  • 1
    http://stackoverflow.com/questions/13988643/case-insensitive-dictionary-with-string-key-type-in-c-sharp?? – Ric Oct 20 '15 at 12:31
  • You can't initialize the inner dictionary without an item in the main dictionary. So when you add the items you initialize the value's dictionary. – Tim Schmelter Oct 20 '15 at 12:33

2 Answers2

0

You have to initialize every dictionary within the outer one calling the constructor-overload for IEqualityComparer.

nCount = new Dictionary<string, Dictionary<string, int>> 
{
    { "myKey", new Dictionary<string, int>(..., myEqualityComparer) }    
};

However mostly you won´t need to fully initialize the dictionary within the constructor. It might be sufficient to simply declare it and add its members later.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
0

You can't initialize the inner dictionary without an item in the main dictionary. So when you add the items you initialize the dictionary by passing the StringComparer to the constructor.

For example:

public mclass()
{
    nCount = new Dictionary<string, Dictionary<string, int>>();
    var innerDict1 = new Dictionary<string, int>(StringComparer.InvariantCultureIgnoreCase);
    innerDict1.Add("Foo", 1);
    nCount.Add("Bah", innerDict1);
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939