I want to create a class which will have two properties, e.g. key & value.
And I want one method which will give me a value based on the key.
So what is the code? I know Hashtable but how to implement it in C#? Can I have a string as a key?
Look at the Dictionary<TKey, TValue> class: http://msdn.microsoft.com/en-us/library/xfhwa508.aspx
Here is the best way implement this (I use Int32 as an example of a type to store):
Dictionary<String,Int32> dictionary = new Dictionary<String,Int32>
{
// this just loads up the list with
// some dummy data - notice that the
// key is a string and the value is an int
{ "one", 1 },
{ "two", 2 },
{ "three", 3 },
};
Now you can grab values from the Dictionary<,> like this:
dictionary["one"]; // returns 1
dictionary["two"]; // returns 2
A Dictionary<string, T> will do all you want.
Use Dictionary<string, TypeOfYourVAlue>
Dictionary(TKey, TValue) Class
There are a couple more implementations as well. There's the HashSet which is designed for set operations and the KeyedCollection which is an easily serializable hash table.
... and also System.Collections.Specialized.NameValueCollection, which is roughly equivalent to Dictionary<string,string>, but allows storing multiple string values under the same key value. To quote MSDN documentation:
This class can be used for headers,
query strings and form data.
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");
}
I have an array of some types
private string[] linkTypes = {
"dog",
"cat",
// and so on ..
};
Yes, I could use an enum but in this case it has to be an array of
strings.
So now I have a List of objects called "LinkElement"
private List<LinkElement> links = new List<LinkElement>();
and these objects have a string property called "Type"
string linkType = links[index].Type;
If linkTypes contains the elements "dog" and "cat", my links can only have "dog" or "cat" as their type.
I want to sort the list "links" by the order of linkTypes.
Means the lists order contains the links with having the type "dog" first and after that the links with the type "cat" come up.
List<LinkElement> sortedLinks = ; // sort links
for (int i = 0; i < sortedLinks.Count; i++)
{
LinkElement currentLink = sortedLinks[i];
Console.WriteLine(currentLink.Type);
}
// Write down dogs first, cats after
Can someone help me out?
Assuming linkTypes (the private string array) is in the same class as links (the list of LinkElement), you can use LINQ's OrderBy with a simple lambda expression:
var sortedLinks = links.OrderBy(le => Array.IndexOf(linkTypes, le.linkType)).ToList()
Comparisons such as "alphabetical order" (string) "bigger number" (numerical types) etc. are accomplished using the IComparable interface. You can implement this interface in your custom class to make instances sort themselves any way you like. Read up on the interface here:
https://msdn.microsoft.com/en-us/library/4d7sx9hd(v=vs.110).aspx
If you have a fixed number of types, then you could use a quick helper method to return an integer for each object depending on its type, and compare the returned integers from each object to determine which one "comes first."
Implement either the IComparer or the IComparable interface. The downside of using the IComparable is that this has to be implemented by the class which is targeted for sorting, which means that in case you want to sort it a different way elsewhere in your code, you will not be able to do so using this mechanism. On the other hand, IComparer can be decoupled from the target class and implemented in multiple ways if you choose to, and depending on the sorting criteria in different parts of your application, you could apply one of these IComparer classes as needed.
https://support.microsoft.com/en-us/help/320727/how-to-use-the-icomparable-and-icomparer-interfaces-in-visual-c
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.
Today I've gone through what indexers are, but I am bit confused. Is there really a need for indexers? What are the advantages of using an indexer..... thanks in advance
I guess the simplest answer is to look at how you'd use (say) List<T> otherwise. Would you rather write:
string foo = list[10];
or
string foo = list.Get(10);
Likewise for dictionaries, would you rather use:
map["foo"] = "bar";
or
map.Put("foo", "bar");
?
Just like properties, there's no real need for them compared with just named methods following a convention... but they make code easier to understand, in my view - and that's one of the most important things a feature can do.
Indexers let you get a reference to an object in a collection without having to traverse the whole collections.
Say you have several thousands of objects, and you need the one before last. Instead of iterating over all of the items in the collection, you simply use the index of the object you want.
Indexers do no have to be integers, so you can use a string, for example, (though you can use any object, so long as the collection supports it) as an indexer - this lets you "name" objects in a collection for later retrieval, also quite useful.
I think zedo got closest to the real reason IMHO that they have added this feature. It's for convenience in the same way that we have properties.
The code is easer to type and easier to read, with a simple abstraction to help you understand.
For instance:
string[] array;
string value = array[0];
List<string> list;
string value = list[0]; //Abstracts the list lookup to a call similar to array.
Dictionary<string, int> map;
int value = map["KeyName"]; //Overloaded with string lookup.
Indexers allow you to reference your class in the same way as an array which is useful when creating a collection class, but giving a class array-like behavior can be useful in other situations as well, such as when dealing with a large file or abstracting a set of finite resources.
yes , they are very use of
you can use indexers to get the indexed object.
Taken from MSDN
Indexers are most frequently implemented in types whose primary purpose is to encapsulate an internal collection or array.
Full Story
for some reason, use indexer can let you create meaningful index to store or map your data. then you can get it from other side by the meaningful index.
using System;
/* Here is a simple program. I think this will help you to understand */
namespace Indexers
{
class Demo
{
int[] a = new int[10];
public int Lengths
{
get
{
return a.Length;
}
}
public int this[int index]
{
get
{
return a[index];
}
set
{
a[index] = value;
}
}
}
class Program
{
static void Main(string[] args)
{
Demo d = new Demo(); // Notice here, this is a simple object
//but you can use this like an array
for (int i = 0; i < d.Lengths; i++)
{
d[i] = i;
}
for (int i = 0; i < d.Lengths; i++)
{
Console.WriteLine(d[i]);
}
Console.ReadKey();
}
}
}
/*Output:
0
1
2
3
4
5
6
7
8
9
*/
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.