I am declaring a Dictionary inside a Dictionary like:
var something = new Dictionary<string, Dictionary<string, Object>>();
I want to be able to access both the outer dictionary as well as the inner dictionary with an IgnoreCase StringComparer.
var something = new Dictionary<string, Dictionary<string, Object>>(StringComparer.InvariantCultureIgnoreCase);
As I am only calling the constructor of the outer dictionary, how can I set the StringComparer of the inner dictionary? If I can't call it's constructor, I can see that there is a property Comparer but I'm not sure how I can get access to the inner dictionary object instead of just a Key or Value.
Any suggestions?
When you declare:
var something = new Dictionary<string, Dictionary<string, Object>>();
It has not created any inner dictionary yet. You will initialize inner dictionary when you add data to it, e.g.
if(!something.ContainsKey("somekey"))
{
something["somekey"] = new Dictionary<string, Object>(StringComparer.InvariantCultureIgnoreCase);
}
Related
I have a variable like below:
var dict = new Dictionary<string, HashSet<string>>();
I want to make sure the values in the HashSet are unique using StringComparer.Ordinal. What would be the syntax for that? Thanks.
Everytime you initialize a new key, the value should be passed an explicit parameter like this:
dict["some key"] = new HashSet<string>(StringComparer.Ordinal);
I want to build a dictionary composed by 2 keys and 1 value. Is that possible?
Dictionary<(key1, key2), Type> dict = new Dictionary<(key1, key2), Type>();
Then I want to find in my dictionary by this 2 keys and get the Type. I tried that key1 and key2 were inside an object like this
Dictionary<Object, Type> dict = new Dictionary<Object, Type>();
Then I added into my dictionary an new instance object with the attributes like this
//myObject has many attributes that are empty and I just fill this 2 ones to build my dict
Object myObject = new Object();
myObject.Key1 = "A";
myObject.Key2 = "B";
dict.Add(myObject, (Type)objType);
But, the object that I want to find is loaded with data from DB and has probably many attributes filled.
The thing is when I use the TryGetValue returns nothing, so I think it's because is looking by the same reference which is not the same.
Well the question, how can I build my dictionary with 2 keys (STRING, STRING) and 1 return value (TYPE) in a easy way.
Thanks
Not sure what you mean by 2 keys. If you want a key containing two values, use Tuple, e.g.
Dictionary<Tuple<int, int>, string>
Another option is to use dictionary of dictionary, e.g.
Dictionary<int, Dictionary<int, string>>
I would use the following:
Dictionary<Tuple<string, string>, Type>
From the msdn page here:
http://msdn.microsoft.com/en-us/library/dd270346.aspx
I believe that the Equals method has been overridden for Tuple, so you should get key matching on the contents of the Tuple rather than the object reference.
Adding to dict would be:
dict.Add(new Tuple<string,string>(myObject.Key1, myObject.Key2), (Type)objType);
I'm trying to hold a lobby system inside of a dictionary.
private Dictionary<string, Dictionary<string, string>> lobbys;
The first string being the Lobby ID, and the dictionary within the dictionary holding the clients usernames in the lobby.
When I try to create a new 'lobby' in the dictionary like so:
lobbys.Add("dSd244SfasdD", null);
( the "dSd244SfasdD" being the unique lobby ID, and null being the null dictionary I've yet to create (since theres no users in it yet))
I get this error: "Object referenced not set to an instance of an object."
I'm unsure as to what I'm doing wrong, and I'm fairly new to C#. Please help. Thanks :)
You must first instantiate the lobbys Dictionary (which holds the Dictionaries):
lobbys = new Dictionary<string, Dictionary<string, string>>();
Then you can add to this lobbys, and when you do so, you should instantiate those inner dictionaries.
lobbys.Add("dsD244SfasD", new Dictionary<string, string>());
Then, when you add to those inner dictionaries:
lobbys["dsD244fasD"].Add("Client1", "Bob Jones");
lobbys["dsD244fasD"].Add("Client2", "Bill James");
You need to instantiate your dictionary.
lobbys = new Dictionary<string, Dictionary<string, string>();
If its a field in your class, you can initialize it at Field or you can initialize it in the class constructor.
You haven't assigned a value to your variable, so it's got the default value of null. (Don't forget that the value of lobbys isn't an object - it's a reference). You could either assign it a value in your constructor, or in the declaration:
private Dictionary<string, Dictionary<string, string>> lobbys
= new Dictionary<string, Dictionary<string, string>>();
(You may well want to make it a readonly variable at the same time - that wouldn't stop you from changing the dictionary's contents, but it would mean that the variable would always refer to the same dictionary.)
You need create an instance of the object first before use it.
private Dictionary<string, Dictionary<string, string>> lobbys = new Dictionary<string, Dictionary<string, string>>();
private Dictionary<string, Dictionary<string, string>> lobbys
= new Dictionary<string, Dictionary<string, string>>();
I have tried reading the other posts on this subject and can't quite figure this out.
I have a list in C# that I want to put in a dictionary with all of the same keys. The list is this
string[] IN ={"Against","Like","Upon","Through","Of","With","Upon","On","Into","From","by","that","In","About","For"
,"Along","Before","Beneath","At","Across","beside","After","Though","Among","Toward","If"};
I want to create and populate a dictionary with the key being "IN" (the name of the array) and then having each string for the array in the dictionary.
This is what I wrote to create the dictionary (which I am not sure is correct):
Dictionary<string, List<string>> wordDictionary = new Dictionary<string, List<string>> ()
But I am not sure how to populate the dictionary.
Any help would be greatly appreciated as this is the first time I have tried to use a dictionary and I am new to C#
An array is string[], not List<string>, so just do this:
Dictionary<string, string[]> wordDictionary = new Dictionary<string, string[]>();
Now you can add your array as usual.
wordDictionary.Add("IN", IN);
Or:
wordDictionary.Add("IN", new string[] {"Against","Like","Upon","Through","Of","With","Upon","On","Into","From","by","that","In","About","For","Along","Before","Beneath","At","Across","beside","After","Though","Among","Toward","If"});
Dictionary.Add("IN", new List<string>(IN));
...if you want to keep the current signature for your dictionary.
If you change it to Dictionary<string, string[]> then you can just:
Dictionary.Add("IN",IN);
You currently have a string array, not a list - so it should be:
Dictionary<string, string[]> wordDictionary = new Dictionary<string,string[]> ()
Then you can just add items like:
wordDictionary.Add("IN" , IN);
Do you really need to convert your array into a string? You could very well use string[] instead of List in your dictionary:
var wordDictionary = new Dictionary<string, string[]>();
wordDictionary.Add("IN", IN);
But if you really want to convert your string array to List:
var wordDictionary = new Dictionary<string, List<string>>();
wordDictionary.Add("IN", IN.ToList());
Another way to add the array (it's not a list) to the dictionary is to use collection initializer:
var wordDictionary = new Dictionary<string, string[]> { "IN", IN };
This is exactly the same as creating the dictionary in a normal way and then calling Add("IN", IN).
I am not a particularly confident programmer yet but am getting there.
My problem is that I have a
static Dictionary<string, Dictionary<string, List<string>>> testDictionary = ...
If the Dictionary doesn't contain the current key (string), I can easily add the key and another dictionary that has been populated, like so...
testDictionary.Add(userAgentResult, allowDisallowDictionary);
That works fine, my problem comes when I am trying to add the inner dictionary if the userAgentResult Key already exists.
I was hoping to do it this way...
testDictionary[userAgentResult].Add(allowDisallowDictionary);
but the .Add method wants two arguments, i.e. the string key and list value. So I went on to write this code...
//this list as the dictionary requires a list
List<string> testDictionaryList = new List<string>();
//this method returns a string
testDictionaryList.Add(regexForm(allowResult, url));
//this will add the key and value to the inner dictionary, the value, and then
//add this value at the userAgentKey
testDictionary[userAgentResult].Add(allowDisallowKey, testDictionaryList);
This also works, my problem is that this dictionary is added to numerous times, and when the inner dictionary already contains the key that is trying to be added, it obviously errors. So when
I would probably simplify this by having one dictionary and joining the keys thus "simulating" a grouping.
string key = userAgentResult + allowDisallowKey;
static Dictionary<string, List<string> testDictionary = ...
testDictionary[key] = list;
You simply need to manage one dictionary.
In this case what you need to do is not adding an entry to the inner dictionary. You need to add the value to the key-value pair of the outer dictionary. Only this time the value happens to be yet another dictionary :)
testDictionary[userAgentResult] = allowDisallowDictionary;
Maybe i don't get your problem. First make sure that dictionaries exist like so:
if (!testDictionary.ContainsKey(userAgentResult))
testDictionary[userAgentResult] = new Dictionary<string, List<string>>();
if (!testDictionary[userAgentResult].ContainsKey(allowDisallowKey))
testDictionary[userAgentResult][allowDisallowKey] = new List<string>();
Then you are free to add items like so:
testDictionary[userAgentResult][allowDisallowKey].Add("some value");
testDictionary[userAgentResult][allowDisallowKey].AddRange(someValueList);
When using nested dictionaries i normally use this approach:
private static Dictionary<string, Dictionary<string, List<string>>> _NestedDictionary = new Dictionary<string, Dictionary<string, List<string>>>();
private void DoSomething()
{
var outerKey = "My outer key";
var innerKey = "My inner key";
Dictionary<string, List<string>> innerDictionary = null;
List<string> listOfInnerDictionary = null;
// Check if we already have a dictionary for this key.
if (!_NestedDictionary.TryGetValue(outerKey, out innerDictionary))
{
// So we need to create one
innerDictionary = new Dictionary<string, List<string>>();
_NestedDictionary.Add(outerKey, innerDictionary);
}
// Check if the inner dict has the desired key
if (!innerDictionary.TryGetValue(innerKey, out listOfInnerDictionary))
{
// So we need to create it
listOfInnerDictionary = new List<string>();
innerDictionary.Add(innerKey, listOfInnerDictionary);
}
// Do whatever you like to do with the list
Console.WriteLine(innerKey + ":");
foreach (var item in listOfInnerDictionary)
{
Console.WriteLine(" " + item);
}
}
You need to do the same for the inner dictionary that you did for the outer one. First check if a list already exists for this key. If not create it. Then use the list that either existed or was created.