Here is my code:
string[] inputs = new[] {"1:2","5:90","7:12","1:70","29:60"};
//Declare Dictionary
var results = new Dictionary<int, int>();
//Dictionary<int, int> results = new Dictionary<int, int>();
foreach(string pair in inputs)
{
string[] split = pair.Split(':');
int key = int.Parse(split[0]);
int value = int.Parse(split[1]);
//Check for duplicate of the current ID being checked
if (results.ContainsKey(key))
{
//If the current ID being checked is already in the Dictionary the Qty will be added
//Dictionary gets Key=key and the Value=value; A new Key and Value is inserted inside the Dictionary
results[key] = results[key] + value;
}
else
{
//if No duplicate is found just add the ID and Qty inside the Dictionary
results[key] = value;
//results.Add(key,value);
}
}
var outputs = new List<string>();
foreach(var kvp in results)
{
outputs.Add(string.Format("{0}:{1}", kvp.Key, kvp.Value));
}
// Turn this back into an array
string[] final = outputs.ToArray();
foreach(string s in final)
{
Console.WriteLine(s);
}
Console.ReadKey();
I want to know if the difference if there is between assigning a key=>value pair in a dictionary.
Method1:
results[key] = value;
Method2:
results.Add(key,value);
In method 1, the function Add() was not called but instead the Dictionary named 'results' assigns somehow sets a Key-Value pair by stating code in method1, I assume that it somehow adds the key and value inside the dictionary automatically without Add() being called.
I'm asking this because I'm currently a student and I'm studying C# right now.
Sir/Ma'am, your answers would be of great help and be very much appreciated. Thank you++
The Dictionary<TKey, TValue> indexer's set method (the one that is called when you do results[key] = value;) looks like:
set
{
this.Insert(key, value, false);
}
The Add method looks like:
public void Add(TKey key, TValue value)
{
this.Insert(key, value, true);
}
The only difference being if the third parameter is true, it'll throw an exception if the key already exists.
Side note: A decompiler is the .NET developers second best friend (the first of course being the debugger). This answer came from opening mscorlib in ILSpy.
If the key exists in 1) the value is overwritten. But in 2) it would throw an exception as keys need to be unique
Related
A standard dictionary would look like this:
public Dictionary<int, DictionarySetup> H = new Dictionary<int, DictionarySetup>()
{
{18000, new DictionarySetup { Some values }},
};
Ranging from A-T, all of these are in a class called DictionaryInit, right now I check the value if there's a match with this boolean:
public Boolean Dictionary_Test(Dictionary<int, DictionarySetup> AccountLexicon)
{
DictionarySetup ClassValues;
if (AccountLexicon.TryGetValue(MapKey, out ClassValues))
{
return true;
}
return false;
}
Now, I'm looking for a more efficient method to loop through each Dictionary and, if there's a match, get that particular dictionary for use in a subsequent method, this is what it looks like now in an if/else:
if(Dictionary_Test(theDictionary.C) == true)
{
Dictionary_Find(Account_String, rowindex, theBSDictionary.C, Cash_Value, txtCurrency.Text);
}
else if (Dictionary_Test(theDictionary.D) == true)
{
Dictionary_Find(Account_String, rowindex, theDictionary.D, Cash_Value, txtCurrency.Text); //Method that makes use of the dictionary values, above dictionary checks only if it exists
}
With dictionaries from A-T, that would be alot of if/else's! Is there a better way to do this? I've found one thread mentioning this same topic, by adding the dictionaries to a dictionary array[] then looping over it, but how do I get the name of the matching dictionary if a match is found or make my second method, Dictionary_Find, use the matching dictionary?
Another possible solution, you could use reflection to get each dictionary from A-T from the DictionaryInit class. Create an array that contains values A-T, loop through the array and use reflection to get the dictionary, and test that dictionary, if you find a match, return that dictionary and exit the loop. Something like:
var dicts = new[]{"A", "B", ......., "T"}
foreach (var dict in dicts)
{
var found = CheckDictionary(theDictionary, dict);
if (found != null)
{
Dictionary_Find(Account_String, rowindex, (Dictionary<int, DictionarySetup>)found, Cash_Value, txtCurrency.Text);
break;
}
}
public static object CheckDictionary(object dictClass, string dictName)
{
var theDictionary = dictClass.GetType().GetProperty(dictName).GetValue(dictClass, null);
return Dictionary_Test(theDictionary) ? theDictionary : null;
}
I've just quickly grabbed some code from a project I've done and modified it to suit but haven't tested it. Might need a few tweaks but hopefully gets you close!
// put dictionary A ~ T to a list of dictionary
List<Dictionary<int, DictionarySetup>> dictionaries = new List<Dictionary<int, DictionarySetup>>{A,B,C, ... , T}; // Replace ... with D,E,F, etc. until T
// iterate each dictionary and if found, exit the loop
foreach(var dict in dictionaries)
{
if(Dictionary_Test(dict))
{
Dictionary_Find(Account_String, rowindex, dict, Cash_Value, txtCurrency.Text);
break;
}
}
I have this public static IDictionary<int, int> dictionaryLIndex;
that after filling it and printing it gives me this:
key = 0, value = 18
key = 1, value = 2
key = 2, value = 1
key = 3, value = 18
key = 4, value = 3
This Dictionary is being created by using:
dictionaryLIndex= ELWIndex.ToDictionary(pair => pair.Key, pair => pair.Value);
ELWIndex is a IList<KeyValuePair<int,int>> So the Key i print from the dictionary is actually the index of a list.
Clarifying that, I need to get the key of the dict based on a value. The thing here is that this values can be repeted so how can i accomplish this? Taking in count that this proccess can be called from time to time.
The final goal is to get that key (index from a list) and search in another list for that position and do something to that index.
Just one thought that just came to me. After getting the first value with that key, can i delete that key-value pair from the dict all together?? So the next time there will be just one key with that value...
So how can i get the key from a value given? and, is this last second thought viable?
Use FirstOrDefault to get the first key-value pair from a dictionary based on a value:
var search = 18;
var kvp = dictionaryLIndex
.Where(p => p.Value == search)
.Cast<KeyValuePair<int,int>?>()
.FirstOrDefault();
If kvp is null, search value is not in the dictionary.
If kvp is not null, use kvp.Key to find the key. You can later delete that key from dictionaryLIndex.
if (kvp.HasValue) {
var key = kvp.Value.Key;
Console.WriteLine("Key = {0}", key);
}
Note: A cast to nullable KeyValuePair<int,int>? is necessary because KeyValuePair<int,int> is a value type, and both its members are value types as well.
Assuming that I understood you correctly and you are trying to create another dictionary that does not contain duplicate values, I think that this could work for you:
Dictionary<int, int> noDuplicates = new Dictionary<int, int>();
foreach (var item in dictionaryLIndex)
{
if (!noDuplicates.ContainsValue(item.Value))
{
noDuplicates.Add(item.Key,item.Value);
}
}
Im trying to figure out how I can create something similar to a dictionary, but where each key can map to several values.
Basically what I need is to be able to assign multiple values to the same key without knowing in advance how many values each key will correspond to. I also need to be able to add values to an existing key on multiple occasions. It would also be nice if I could detect when a key + value combination already exists.
An example of how the program should work:
list.Add(1,5);
list.Add(3,6);
list.Add(1,7);
list.Add(5,4);
list.Add(1,2);
list.Add(1,5);
This should ideally produce a table like this:
1: 5, 7, 2
3: 6
5: 4
Is there any existing construction in C# that I can use for this or do I have to implement my own class? Implementing the class would probably not be a big problem, but Im a bit short on time so it would be nice if I could use something that already exists.
Quick Solution
As you have already mentioned, a Dictionary would be the best type to use. You can specify both the key type and value type to meet your needs, in your case you want an int key and a List<int> value.
This is easy enough to create:
Dictionary<int, List<int>> dictionary = new Dictionary<int, List<int>>();
The challenge then comes with how you add records, you cannot simply do Add(key, value) because that will cause conflict which duplicate keys. So you have to first retrieve the list (if it exists) and add to that:
List<int> list = null;
if (dictionary.ContainsKey(key))
{
list = dictionary[key];
}
else
{
list = new List<int>();
dictionary.Add(key, list);
}
list.Add(newValue);
Preferred Solution
This is obviously a few too many lines to use each time you want to add an item, so you would want to throw that into a helper function, or my preference would be to create your own class that extends the functionality of Dictionary. Something like this:
class ListDictionary<T1, T2> : Dictionary<T1, List<T2>>
{
public void Add(T1 key, T2 value)
{
if (this.ContainsKey(key))
{
this[key].Add(value);
}
else
{
List<T2> list = new List<T2>() { value };
this.Add(key, list);
}
}
public List<T2> GetValues(T1 key)
{
if(this.ContainsKey(key))
return this[key];
return null;
}
}
Which you can then use as easy as you originally wanted:
ListDictionary<int, int> myDictionary = new ListDictionary<int, int>();
myDictionary.Add(1,5);
myDictionary.Add(3,6);
//...and so on
Then to get the list of values for your desired key:
List<int> keyValues = myDictionary.GetValues(key);
//check if NULL before using, NULL means the key does not exist
//alternatively you can check if the key exists with if (myDictionary.ContainsKey(key))
You can create a dictionary of Lists quite easily e.g.
Dictionary<int, List<int>> dictionary = new Dictionary<int, List<int>>()
An Alternative if you have created a list of items and want to separate them into groups with different keys, which serves much the same purpose is the Lookup class.
Dictionary<int, List<int>> dictionary = new Dictionary<int, List<int>>();
public void AddIfNotExistInDic(int key, int Value) {
List<int> list = null;
if (dictionary.ContainsKey(key)) {
list = dictionary[key];
}
else {
list = new List<int>();
dictionary.Add(key, list);
}
if (!list.Contains(Value)) {
list.Add(Value);
}
}
You can use Dictionary<TKey, TValue>, the TKey would be int and TValue would be List<int>, You can add as many element in List as it grow autmatically.
Dictionary <int, List<int>> dic = new Dictionary<int, List<int>>();
The way you can access the value would change, you can for instance add element in dictionary like
void AddToYourCustomDictionary(int key, int someValue)
{
if(!dic.ContainsKey(key))
{
dic.Add(key, new List<int>());
dic[key].Add(someValue);
}
else
dic[key].Add(someValue); //Adding element in existing key Value pair
}
To access element in Dictionary Key -> value i.e list,
Console.WriteLine(dic[key][indexOfList]);
I have a Hashtable, which contains values like this:
key: 123456 value: UV
key: 654321 value: HV
...
Now I want to check if a combination already exists and dont insert anything. So if my key is 123456 and my value is UV, no new entry is added. How could I do this?
Thanks :-)
A Hashtable (or, preferably, a Dictionary<TKey, TValue>) contains exactly one value for a stored key. So, if you add a new key-value-pair to the collection, you can simply check for the existence of the key before doing so:
static bool AddIfNotContainsKey<K,V>(this Dictionary<K,V> dict, K key, V value)
{
if (!dict.ContainsKey(key))
{
dict.Add(key, value);
return true;
}
return false;
}
Example:
var dict = new Dictionary<string, string>();
dict.AddIfNotContainsKey("123456", "UV"); // returns true
dict.AddIfNotContainsKey("654321", "HV"); // returns true
dict.AddIfNotContainsKey("123456", "??"); // returns false
string result = dict["123456"]; // result == "UV"
Use the Contains method of the Hashtable, and as #dtb says the Hashtable contains one value for a key, so in your case if you need to have things like ("key1","value1"), ("key1","value2") then maybe is more apropiate store the pair as the key making the existence of this values perfectly valid.
you could make a function with something like this, I have tried it and it is working.
class Program
{
static void Main()
{
Dictionary<string, bool> d = new Dictionary<string, bool>();
d.Add("cat", true);
d.Add("dog", false);
d.Add("sprout", true);
// A.
// We could use ContainsKey.
if (d.ContainsKey("dog"))
{
// Will be 'False'
bool result = d["dog"];
Console.WriteLine(result);
}
// B.
// Or we could use TryGetValue.
bool value;
if (d.TryGetValue("dog", out value))
{
// Will be 'False'
bool result = value;
Console.WriteLine(result);
}
}
}
I've got a hashtable that I want to update from a second hashtable. For any of the keys that match I want to copy the value over. The problem I have is when I enumerate the hashtable keys and try to cast each to a string I receive an exception about casting a Guid to a String. Well it's the string I want. When you use the index operator with something like hashtable["FirstName"] then I expect FirstName to be the key. It might use Guids underneath I guess but I need to get out the string for the key, the key value.
private void UpdateSharePointFromInfoPath(Hashtable infopathFields)
{
// Go through all the fields on the infopath form
// Invalid Cast Exception Here
foreach (String fieldName in infopathFields.Keys)
{
// If the same field is on sharepoint
if (workflowProperties.Item.Fields.ContainsField(fieldName))
{
// Update the sharepoint field with the new value from infopath
workflowProperties.Item[fieldName] = infopathFields[fieldName];
}
}
// Commit the changes
workflowProperties.Item.Update();
}
EDIT
I don't create either of these hashtables. The keys have strings somewhere because I can put the field name in like the following and get the value of the field out. I'm trying to make a shorthand way of doing the following for every field:
workflowProperties.Item["FirstName"] = infopathFields["FirstName"];
workflowProperties.Item["LastName"] = infopathFields["LastName"];
workflowProperties.Item["Address"] = infopathFields["Address"];
workflowProperties.Item["DOB"] = infopathFields["DOB"];
ect...
EDIT
It's been said that the hashtable uses Guids, but it also obviously has a string inside else I wouldn't be able to do infopathFields["FirstName"]. It's the value on the string I pass in there that I want.
Every item is a Key/Value pair of format DictionaryEntry
foreach (DictionaryEntry de in infopathFields)
{
string fieldName = de.Key as string;
if (workflowProperties.Item.Fields.ContainsField(fieldName))
{
workflowProperties.Item[fieldName] = infopathFields[fieldName];
}
}
workflowProperties.Item.Update();
The standard version of the Hashtable can have different type keys, so most of your keys may be strings, but some of your keys may be GUIDs. I'm willing to bet that is the case and is causing your issue. The following little console app demonstrates the problem.
static void Main(string[] args)
{
System.Collections.Hashtable htable = new System.Collections.Hashtable();
htable.Add("MyName", "WindyCityEagle");
htable.Add("MyAddress", "Here");
htable.Add(new Guid(), "That Was My Guid");
int loopCount = 0;
foreach (string s in htable.Keys)
{
Console.WriteLine(loopCount++.ToString());
Console.WriteLine(htable[s]);
}
}
You'll get the exact same exception that you're reporting here.
My suggestion to fix the problem would be to go with the following
private void UpdateSharePointFromInfoPath(Hashtable infopathFields)
{
// Go through all the fields on the infopath form
// Invalid Cast Exception Here
foreach (object key in infopathFields.Keys)
{
string wfpKey = key.ToString();
// If the same field is on sharepoint
if (workflowProperties.Item.Fields.ContainsField(wfpKey))
{
// Update the sharepoint field with the new value from infopath
workflowProperties.Item[wfpKey] = infopathFields[key];
}
}
// Commit the changes
workflowProperties.Item.Update();
}
What creates the Hashtable? the key is actually an object so it sounds like whatever populated it has no implicit cast to a string
If the type of the values of infopathFields is a Guid then the types of the values of workflowProperties will have to be Guids. I can't see from the snippet what workflowProperties is defined as.
To convert a Guid to a string use Guid.ToString()
The objects stored in the hashtable are Guid objects, so to get a string you need to call ToString() on the object you get from the key enumerator. I would also recommend using the generic Dictionary<K,V> class instead of Hashtable, as that would catch problems like this at compile time rather than runtime.
To get largest integer key from Hash table:
public class Example
{
public void hashTableMethod()
{
Hashtable ht = new Hashtable();
ht.Add(5002894, "Hemant Kumar");
ht.Add(5002895, "Himanshee Ratnakar");
ht.Add(5002896, "Pooja Bhatnagar");
ht.Add(5002897, "Hina Saxena");
ht.Add(5002898, "Kanika Aneja");
ht.Add(5002899, "Hitesh Chaudhary");
Console.Write("\nNumber of Key-Value pair elements in HashTable are : {0}",ht.Count);
Console.WriteLine("Elements in HashTable are: ");
ICollection htkey = ht.Keys;
foreach (int key in htkey)
{
Console.WriteLine("{0}. {1}",key,ht[key]);
}
string ch="n";
do
{
Console.Write("\n\nEnter the name to check if it is exist or not, if not then it will add: ");
string newName=Console.ReadLine();
if(ht.ContainsValue(newName))
{
Console.Write("\nYour Name already Exist in the list!!");
}
else
{
Console.Write("\nSorry that name doesn't exist but it will be added!!");
int getKey = 0;
int[] htk= new int[ht.Count];
ht.Keys.CopyTo(htk,0);
string[] val=new string[ht.Count];
ht.Values.CopyTo(val,0);
Array.Sort(htk,val);
foreach (int id in htk)
{
getKey = id;
}
ht.Add(getKey+1,newName);
}
Console.Write("\nDo you want to search more??(y/n) :");
ch=Console.ReadLine();
}while(ch=="y"||ch=="Y");
Console.Write("\nNew List Items: \n");
ICollection htkeys = ht.Keys;
foreach (int key in htkeys)
{
Console.WriteLine("{0}. {1}",key,ht[key]);
}
}
}