Dictionary<string, double> state = new Dictionary<string, double>(50);
state.Add("Alabama", 0.0570);
state.Add("Alaska", 0.1167);
state.Add("Arizona", 0.0592);
state.Add("Arkansas", 0.0835);
state.Add("California", 0.0739);
state.Add("Colorado", 0.0272);
state.Add("Connecticut", 0.06540);
state.Add("Delaware", 0.0825);
state.Add("Florida", 0.0503);
state.Add("Georgia", 0.0562);
state.Add("Hawaii", 0.0985);
state.Add("Idaho", 0.0736);
state.Add("Illinois", 0.0562);
state.Add("Indiana", 0.0648);
state.Add("Iowa", 0.0591);
state.Add("Kansas", 0.0654);
state.Add("Kentucky", 0.0734);
state.Add("Louisiana", 0.0685);
state.Add("Maine", 0.0770);
state.Add("Maryland", 0.0559);
state.Add("Massachusetts", 0.0630);
state.Add("Michigan", 0.0672);
state.Add("Minnesota", 0.0802);
state.Add("Mississippi", 0.0740);
state.Add("Missouri", 0.0517);
state.Add("Montana", 0.0708);
state.Add("Nebraska", 0.0610);
state.Add("Nevada", 0.0612);
state.Add("New Hampshire", 0.0387);
state.Add("New Jersey", 0.0661);
state.Add("New Mexico", 0.0826);
state.Add("New York", 0.0676);
state.Add("North Carolina", 0.0726);
state.Add("North Dakota", 0.0711);
state.Add("Ohio", 0.0609);
state.Add("Oklahoma", 0.0621);
state.Add("Oregon", 0.0576);
state.Add("Pennsylvania", 0.0617);
state.Add("Rhode Island", 0.0640);
state.Add("South Carolina", 0.0619);
state.Add("South Dakota", 0.0423);
state.Add("Tennessee", 0.0539);
state.Add("Texas", 0.0438);
state.Add("Utah", 0.0728);
state.Add("Vermont", 0.1060);
state.Add("Virginia", 0.0563);
state.Add("Washington", 0.0648);
state.Add("West Virginia", 0.0834);
state.Add("Wisconsin", 0.0693);
state.Add("Wyoming", 0.0778);
string stateKey = textBox1.Text.Trim().ToUpper();
if (state.ContainsKey(stateKey))
{
StateTax = state[stateKey];
}
else
{
string messageBoxText = "Missing rate for state " + stateKey;
MessageBox.Show(messageBoxText);
return;
}
So this is what i have so far, i cant get StateTax To take the value of one of my dictionary Values.This usually doesn't take me that long but my brain is just freezing lately on thinking. Whats the best way to write this?
You are upper casing:
string stateKey = textBox1.Text.Trim().ToUpper();
but dictionary keys are in proper caps:
"Wyoming"
Either place in dictionary as all lower or upper case, and do the same to your entered value, OR make entered text first caps (the former is preferable)
UPDATE: or even better! use Anthony's or Ed's idea of a case insensitive dictionary!
You're calling ToUpper on your key, but you didn't add the keys to the dictionary in all caps:
string stateKey = textBox1.Text.Trim().ToUpper();
"ALABAMA" != "Alabama", so you will need to either:
Call ToUpper() or ToLower() on your user input and enter your keys accordingly, or
Use a case insensitive compare <-- Better option
The Dictionary<K,V> class will take an IEqualityComparer<T> in one of its constructors. Use it to define how to compare key values.
var caseInsensitiveDictionary = new Dictionary<string, int>(
StringComparer.OrdinalIgnoreCase);
The StringComparer class implements the IEqualityComparer interface.
Your dictionary stores the keys like "Abc", but you are attempting to retrieve the value using the key "ABC". To fix your specific dilemna, specify a comparer that ignores case completely.
var stateTaxTable = new Dictionary<string, decimal>(StringComparer.CurrentCultureIgnoreCase);
Also notice I'm making the value a decimal as a suggestion. It is more fitting of storing a value to be used in a financial calculation. You would store it in the dictionary using the M suffix on the value. Example:
stateTaxTable.Add("Some State", 0.075M);
If you are multiplying a price by this value, you'd want the price to be a decimal, as well. Again, these are suggestions, but it's good to get in the habit of using the proper type for financial data.
The .ToUpper() is your problem.
Whatever's in the textbox is being normalized to uppercase, but the keys are case-sensitive.
Your are converting the state input to upper case. You will never find the entry in the dictionary.
Either (1) change code to use upper case state names or (2) remove the ToUpper and create the dictionary with a case insensitive comparer.
Or you can use
String stateKey =
CultureInfo.CurrentCulture.TextInfo.ToTitleCase(textbox1.Text);
Related
Before adding a new tuple, I want to check if a list already contains that tuple and avoiding adding it to the list again, how would I got about doing this? I'm aware for integers and strings you would just write list.Contains(2) or list.Contains("2"), but i'm not sure what syntax to use when checking for tuples.
I've tried these two so far (snippets). (combination is a list of tuples<char, char>)
if(!combinations.Contains(Tuple<char, char>(s[i], chr)))
{
combinations.Add(new Tuple<char, char>(s[i], chr));
}
if(!combinations.Contains(Tuple<char, char> s[i], chr))
{
combinations.Add(new Tuple<char, char>(s[i], chr));
}
Adding works fine so I thought it would be the same when comparing. Any help with syntax or logic would be great, thanks :)
Tuples already implement the appropriate equality, so you shouldn't need to do anything except create the value, and then use .Contains. However:
you may prefer ValueTuple<...> over Tuple<...>, and
if order doesn't matter, you may prefer HashSet<T>, which handles uniqueness internally
For example:
// note that (char, char) is a ValueTuple<char, char>
private readonly HashSet<(char,char)> combinations = new();
//...
combinations.Add((x, y)); // adds the x/y tuple if it doesn't exist
You can also name the parts here:
private readonly HashSet<(char X,char Y)> combinations = new();
which will allow you to use .X and .Y on values, via compiler voodoo.
In C#, you can use the Contains() method to check if a list contains a specific tuple. Here is an example:
// List of tuples
var tupleList = new List<(char, char)>()
{
('a', 'b'),
('c', 'd'),
('e', 'f')
};
// Tuple to search for
var searchTuple = ('a', 'b');
// Check if the list contains the tuple
if (tupleList.Contains(searchTuple))
{
Console.WriteLine("The list contains the tuple");
}
else
{
Console.WriteLine("The list does not contain the tuple");
}
My dictionary:
Dictionary<double, string> dic = new Dictionary<double, string>();
How can I return the last element in my dictionary?
What do you mean by Last? Do you mean Last value added?
The Dictionary<TKey,TValue> class is an unordered collection. Adding and removing items can change what is considered to be the first and last element. Hence there is no way to get the Last element added.
There is an ordered dictionary class available in the form of SortedDictionary<TKey,TValue>. But this will be ordered based on comparison of the keys and not the order in which values were added.
EDIT
Several people have mentioned using the following LINQ style approach
var last = dictionary.Values.Last();
Be very wary about using this method. It will return the last value in the Values collection. This may or may not be the last value you added to the Dictionary. It's probably as likely to not be as it is to be.
Dictionaries are unordered collections - as such, there is no concept of a first or last element. If you are looking for a class that behaves like a dictionary but maintains the insertion order of items, consider using OrderedDictionary.
If you are looking for a collection that sorts the items, consider using SortedDictionary<TKey,TValue>.
If you have an existing dictionary, and you are looking for the 'last' element given some sort order, you could use linq to sort the collection, something like:
myDictionary.Values.OrderBy( x => x.Key ).Last();
By wary of using Dictionary.Keys.Last() - while the key list is sorted using the default IComparer for the type of the key, the value you get may not be the value you expect.
I know this question is too old to get any upvotes, but I didn't like any of the answers so will post my own in the hopes of offering another option to future readers.
Assuming you want the highest key value in a dictionary, not the last inserted:
The following did not work for me on .NET 4.0:
myDictionary.Values.OrderBy( x => x.Key ).Last();
I suspect the problem is that the 'x' represents a value in the dictionary, and a value has no key (the dictionary stores the key, the dictionary values do not). I may also be making a mistake in my usage of the technique.
Either way, this solution would be slow for large dictionaries, probably O(n log n) for CS folks, because it is sorting the entire dictionary just to get one entry. That's like rearranging your entire DVD collection just to find one specific movie.
var lastDicVal = dic.Values.Last();
is well established as a bad idea. In practice, this solution may return the last value added to the dictionary (not the highest key value), but in software engineering terms that is meaningless and should not be relied upon. Even if it works every time for the rest of eternity, it represents a time bomb in your code that depends on library implementation detail.
My solution is as follows:
var lastValue = dic[dic.Keys.Max()];
The Keys.max() function is much faster than sorting O(n) instead of O(n log n).
If performance is important enough that even O(n) is too slow, the last inserted key can be tracked in a separate variable used to replace dic.Keys.Max(), which will make the entire lookup as fast as it can be, or O(1).
Note: Use of double or float as a key is not best practice and can yield surprising results which are beyond the scope of this post. Read about "epsilon" in the context of float/double values.
If you're using .NET 3.5, look at:
dic.Keys.Last()
If you want a predictable order, though, use:
IDictionary<int, string> dic = new SortedDictionary<int, string>();
Instead of using:
Dictionary<double, string>
...you could use:
List<KeyValuePair<double, string>>
This would allow you to use the indexer to access the element by order instead of by key.
Consider creating a custom collection that contains a reference in the Add method of the custom collection. This would set a private field containing the last added key/value(or both) depending on your requirements.
Then have a Last() method that returns this. Here's a proof of concept class to show what I mean (please don't knock the lack of interface implementation etc- it is sample code):
public class LastDictionary<TKey, TValue>
{
private Dictionary<TKey, TValue> dict;
public LastDictionary()
{
dict = new Dictionary<TKey, TValue>();
}
public void Add(TKey key, TValue value)
{
LastKey = key;
LastValue = value;
dict.Add(key, value);
}
public TKey LastKey
{
get; private set;
}
public TValue LastValue
{
get; private set;
}
}
From the docs:
For purposes of enumeration, each item
in the dictionary is treated as a
KeyValuePair structure representing a
value and its key. The order in which
the items are returned is undefined.
So, I don't think you can rely on Dictionary to return the last element.
Use another collection. Maybe SortedDictionary ...
If you just want the value, this should work (assuming you can use LINQ):
dic.Values.Last()
You could use:
dic.Last()
But a dictionary doesn't really have a last element (the pairs inside aren't ordered in any particular way). The last item will always be the same, but it's not obvious which element it might be.
With .Net 3.5:
string lastItem = dic.Values.Last()
string lastKey = dic.Keys.Last()
...but keep in mind that a dictionary is not ordered, so you can't count on the fact that the values will remain in the same order.
A dictionary isn't meant to be accessed in order, so first, last have no meaning. Do you want the value indexed by the highest key?
Dictionary<double, string> dic = new Dictionary<double, string>();
double highest = double.MinValue;
string result = null;
foreach(double d in dic.keys)
{
if(d > highest)
{
result = dic[d];
highest = d;
}
}
Instead of using Linq like most of the other answers suggest, you can just access the last element of any Collection object via the Count property (see ICollection.Count Property for more information).
See the code here for an example of how to use count to access the final element in any Collection (including a Dictionary):
Dictionary<double, string> dic = new Dictionary<double, string>();
var lastElementIndex = dic.Count - 1;
var lastElement = dic[lastElementIndex];
Keep in mind that this returns the last VALUE, not the key.
I've some problems using the Dictionary. How can I get the value back from the Dictionary
I have stored some data in the Dictionary
Dictionary<UserSettings.Languages, string> objectiveLanguages
= new Dictionary<UserSettings.Languages, string>();
objectiveLanguages.Add(UserSettings.Languages.English, objectiveNameEnglish);
objectiveLanguages.Add(UserSettings.Languages.German, objectiveNameGerman);
Could someone explain me, how to retreive the stored value again?
Two options:
You know that the value will be present.
string str = objectiveLanguages[UserSettings.Languages.English];
return str;
You don't know that the value will be present, or you'd like to throw your own exception.
string str;
if(objectiveLanguages.TryGet(UserSettings.Languages.English, out str))
return str;
else
throw new ArgumentException(); // or return null, or whatever.
The choice between these depends on circumstances. Since you're dealing with an enum (or equivalent), the first should probably suffice. If the user was, say, entering data, on the other hand, I'd probably go with the second. It's a similar decision to that of using int.Parse versus int.TryParse.
Console.WriteLine("For key UserSettings.Languages.English, value = {0}.",
objectiveLanguages[UserSettings.Languages.English]);
/* returns the value of this key, if present.
*/
Ref the MSDN documentation here for more info.
Dictionary<UserSettings.Languages, string> objectiveLanguages
= new Dictionary<UserSettings.Languages, string>();
objectiveLanguages.Add(UserSettings.Languages.English, objectiveNameEnglish);
objectiveLanguages.Add(UserSettings.Languages.German, objectiveNameGerman);
// get some value out of the dict
string dictContent = objectiveLanguages[UserSettings.Languages.English];
Use square brackets with a key inside. For example:
// returns objectiveNameEnglish
var retrievedValue = objectiveLanguages[UserSettings.Languages.English];
For every pair you add, the first item is the key and the second item is the value mapped to it. MSDN has good examples https://msdn.microsoft.com/en-us/library/xfhwa508(v=vs.110).aspx
I have a dictionary of string people (key) and string addresses (value). I want to have an if statement that returns true if any key in my dictionary contains the substring 'anders'. Is there any way to do this? I have tried dict.ContainsKey("anders") but that just returns true if any key is explicitly named 'anders'. I would like it to return true even if the key is anderson or andersen. I know this is a pretty strange case but i need it for a purpose.
Thanks
You'll have to iterate over the collection and check each one. The LINQ Any method makes this fairly simple:
dict.Keys.Any(k => k.Contains("anders"))
Everyone has already pointed out the obvious (and correct) Any method, but one note: Using String.Contains as the predicate will only return true if the case of the substring is also correct. To do a case-insensitive search, use a simple Regex:
dict.Keys.Any(x => Regex.IsMatch(x, "(?i)anders"));
Or use IndexOf with the StringComparison argument (as in Case insensitive 'Contains(string)'):
dict.Keys.Any(x => x.IndexOf("anders", StringComparison.InvariantCultureIgnoreCase) >= 0);
There is no "wildcard search" for dictionary keys. In order to do this type of search, you are going to lose the O(constant) search that a dictionary gives you.
You'll have to iterate over the keys of the dictionary and look for those that contain the substring you require. Note that this will be an O(n*X) iteration, where n is the number of keys and X is the average size of your key string.
There's a nifty one-liner that will help:
bool containsKey = myDictionary.Keys.Any(x => x.Contains("mySubString"));
But it's a heavy operation.
var pair = dict.FirstOrDefault(kvp => kvp.Key.Contains("anders"));
if(dict.Keys.Any(k=>k.Contains("anders")))
{
//do stuff
}
You can iterate the keys of the dictionary and check each if it contains the string:
bool found = false;
foreach (string key in dict.Keys)
{
if (key.Contains("anders"))
{
found = true;
break;
}
}
or using LINQ:
bool found = dict.Keys.Any(key => key.Contains("anders"));
What is the difference in Dictionary.add(key, value) and Dictionary[key] = value?
I've noticed that the last version does not throw an ArgumentException when inserting a duplicate key, but is there any reason to prefer the first version?
Edit: Does anyone have an authoritative source of information about this? I've tried MSDN, but it is as always a wild goose chase :(
The performance is almost a 100% identical. You can check this out by opening the class in Reflector.net
This is the This indexer:
public TValue this[TKey key]
{
get
{
int index = this.FindEntry(key);
if (index >= 0)
{
return this.entries[index].value;
}
ThrowHelper.ThrowKeyNotFoundException();
return default(TValue);
}
set
{
this.Insert(key, value, false);
}
}
And this is the Add method:
public void Add(TKey key, TValue value)
{
this.Insert(key, value, true);
}
I won't post the entire Insert method as it's rather long, however the method declaration is this:
private void Insert(TKey key, TValue value, bool add)
And further down in the function, this happens:
if ((this.entries[i].hashCode == num) && this.comparer.Equals(this.entries[i].key, key))
{
if (add)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
}
Which checks if the key already exists, and if it does and the parameter add is true, it throws the exception.
So for all purposes and intents the performance is the same.
Like a few other mentions, it's all about whether you need the check, for attempts at adding the same key twice.
Sorry for the lengthy post, I hope it's okay.
The first version will add a new KeyValuePair to the dictionary, throwing if key is already in the dictionary. The second, using the indexer, will add a new pair if the key doesn't exist, but overwrite the value of the key if it already exists in the dictionary.
IDictionary<string, string> strings = new Dictionary<string, string>();
strings["foo"] = "bar"; //strings["foo"] == "bar"
strings["foo"] = string.Empty; //strings["foo"] == string.empty
strings.Add("foo", "bar"); //throws
To answer the question first we need to take a look at the purpose of a dictionary and underlying technology.
Dictionary is the list of KeyValuePair<Tkey, Tvalue> where each value is represented by its unique key. Let's say we have a list of your favorite foods. Each value (food name) is represented by its unique key (a position = how much you like this food).
Example code:
Dictionary<int, string> myDietFavorites = new Dictionary<int, string>()
{
{ 1, "Burger"},
{ 2, "Fries"},
{ 3, "Donuts"}
};
Let's say you want to stay healthy, you've changed your mind and you want to replace your favorite "Burger" with salad. Your list is still a list of your favorites, you won't change the nature of the list. Your favorite will remain number one on the list, only it's value will change. This is when you call this:
/*your key stays 1, you only replace the value assigned to this key
you alter existing record in your dictionary*/
myDietFavorites[1] = "Salad";
But don't forget you're the programmer, and from now on you finishes your sentences with ; you refuse to use emojis because they would throw compilation error and all list of favorites is 0 index based.
Your diet changed too! So you alter your list again:
/*you don't want to replace Salad, you want to add this new fancy 0
position to your list. It wasn't there before so you can either define it*/
myDietFavorites[0] = "Pizza";
/*or Add it*/
myDietFavorites.Add(0, "Pizza");
There are two possibilities with defining, you either want to give a new definition for something not existent before or you want to change definition which already exists.
Add method allows you to add a record but only under one condition: key for this definition may not exist in your dictionary.
Now we are going to look under the hood. When you are making a dictionary your compiler make a reservation for the bucket (spaces in memory to store your records). Bucket don't store keys in the way you define them. Each key is hashed before going to the bucket (defined by Microsoft), worth mention that value part stays unchanged.
I'll use the CRC32 hashing algorithm to simplify my example. When you defining:
myDietFavorites[0] = "Pizza";
What is going to the bucket is db2dc565 "Pizza" (simplified).
When you alter the value in with:
myDietFavorites[0] = "Spaghetti";
You hash your 0 which is again db2dc565 then you look up this value in your bucket to find if it's there. If it's there you simply rewrite the value assigned to the key. If it's not there you'll place your value in the bucket.
When you calling Add function on your dictionary like:
myDietFavorite.Add(0, "Chocolate");
You hash your 0 to compare it's value to ones in the bucket. You may place it in the bucket only if it's not there.
It's crucial to know how it works especially if you work with dictionaries of string or char type of key. It's case sensitive because of undergoing hashing. So for example "name" != "Name". Let's use our CRC32 to depict this.
Value for "name" is: e04112b1
Value for "Name" is: 1107fb5b
Dictionary.Add(key, value) and Dictionary[key] = value have different purposes:
Use the Add method to add new key/value pair, existing keys will not be replaced (an ArgumentException is thrown).
Use the indexer if you don't care whether the key already exists in the dictionary, in other words: add the key/value pair if the the key is not in the dictionary or replace the value for the specified key if the key is already in the dictionary.
Yes, that is the difference, the Add method throws an exception if the key already exists.
The reason to use the Add method is exactly this. If the dictionary is not supposed to contain the key already, you usually want the exception so that you are made aware of the problem.
To insert the Value into the Dictionary
Dictionary<string, string> dDS1 = new Dictionary<string, string>();//Declaration
dDS1.Add("VEqpt", "aaaa");//adding key and value into the dictionary
string Count = dDS1["VEqpt"];//assigning the value of dictionary key to Count variable
dDS1["VEqpt"] = Count + "bbbb";//assigning the value to key
Given the, most than probable similarities in performance, use whatever feel more correct and readable to the piece of code you're using.
I feel an operation that describes an addition, being the presence of the key already a really rare exception is best represented with the add. Semantically it makes more sense.
The dict[key] = value represents better a substitution. If I see that code I half expect the key to already be in the dictionary anyway.
One is assigning a value while the other is adding to the Dictionary a new Key and Value.