Hi im doing a school assignment, and I need to convert this JAVA code to C#
private Map<ItemID, ProductDescription> descriptions = new HashMap()<ItemID, ProductDescription>;
Is it possible to make a straight conversion?
I've already decided to make ItemID into an int, and ProductDescription is a class.
Yes, of course you can.
Please look into following examples:
IDictionary<int, string> h = new Dictionary<int, string>();
h.Add(1, "a");
h.Add(2, "b");
h.Add(3, "c");
SortedList<int, string> s = new SortedList<int, string>();
s.Add(1, "a");
s.Add(2, "b");
I think this is what you are looking for.
You could use a Dictionary<int, ProductDescription> instead.
Dictionary<TKey, TValue> Class
Represents a collection of keys and values. The key must be unique.
private Dictionary<ItemID, ProductDescription> descriptions = new Dictionary<ItemID, ProductDescription>();
The hasmap indeed allows for one null key entry. In the (rare?) case you would need this I'd simply create a special ItemID and use that for the null key.
You could ofcourse make a dictionary descendant with null key support, but that would be overdoing it imho ;-)
Yes, just replace HashMap with Dictionary. You might want to type the variable as an IDictionary (in the same spirit as the Java code), but that's not strictly necessary.
Yes, You can do the conversion using a Dictionary instead of HashMap. And of course it is more effective to get the idea of each code segment and convert. Trying to convert line by line is not recommended since you may miss a better way that can be used to resolve the problem.
There are many options.
There is an
Hashtable in C#
KeyValuePair So it can be List<KeyValuePair<T,U>>
Dictionary //Preferred
This is a good match but,
private IDictionary<ItemID, ProductDescription> descriptions
= new Dictionary<ItemID, ProductDescription>();
Note
HashMap will accept null key values, where as Dictionary will not.
If you really want to support null key values, I'd like to see you reasoning before attempting a perfect .Net HashMap implementation.
Related
I have the following hashtable on my application:
System.Collections.Hashtable colunas = new System.Collections.Hashtable();
colunas.Add("Nome", "Nome");
colunas.Add("Departamento", "Departamento");
colunas.Add("Cargo", "Cargo");
After, I pass this hashtable as parameter to a function and when I pass through the hashtable in a foreach I get the following results:
Departamento
Nome
Cargo
Why the result is in that order and not in this:
Nome
Departamento
Cargo
-- EDIT --
Ok, I understood the reason, but what can I use instead of hashtable to preserve the insertion order?
Hashtables do not preserve insertion order.
Instead, they use an unspecified order based on the hashcodes of the keys.
This answer is "promoted" from a comment, by request from the Original Poster.
If it is important for you to keep the order of insertion, you might want to simply use a List<> whose elements are somehow pairs of strings. Two solutions are natural, either:
var colunas = new List<KeyValuePair<string, string>>();
colunas.Add(new KeyValuePair<string, string>("Nome", "Nome"));
colunas.Add(new KeyValuePair<string, string>("Departamento", "Departamento"));
colunas.Add(new KeyValuePair<string, string>("Cargo", "Cargo"));
or:
var colunas = new List<Tuple<string, string>>();
colunas.Add(Tuple.Create("Nome", "Nome"));
colunas.Add(Tuple.Create("Departamento", "Departamento"));
colunas.Add(Tuple.Create("Cargo", "Cargo"));
There's a technical difference between KeyValuePair<,> and Tuple<,> because the former is a struct (value type) and the latter is a class (reference type), but since both KeyValuePair<,> and Tuple<,> are immutable types, that is probably unimportant. Then decide if the property names Key/Value or Item1/Item2 are best suited for your use.
Note that if you use this solution, you don't get the benefits a hashtable offers. You don't get fast lookup on key. And there's no guarantee that the List<> can't have many entries with the same "key" string (first component of the pair). That string could even be null.
If you want to sort the List<> after all, at some point, the call colunas.Sort(); (no comparer argument given) will work for Tuple<,> (lexicographic order) but not for KeyValuePair<,>. Of course if you wanted the collection sorted all the time by keys, you would use SortedDictionary<string, string> as suggested by another answer.
Hashtable represents a collection of key/value pairs that are organized based on the hash code of the key.
but what can I use instead of hashtable to preserve the insertion order?
You have a choice:
System.Collections.Generic.SortedList<TKey, TValue>
System.Collections.Generic.SortedDictionary<TKey, TValue>
See the remarks section here for the differences.
I wanted to add a KeyValuePair<T,U> to a Dictionary<T, U> and I couldn't. I have to pass the key and the value separately, which must mean the Add method has to create a new KeyValuePair object to insert, which can't be very efficient. I can't believe there isn't an Add(KeyValuePair<T, U>) overload on the Add method. Can anyone suggest a possible reason for this apparent oversight?
You can use the IDictionary<TKey,TValue> interface which provides the Add(KeyValuePair<TKey,TValue>) method:
IDictionary<int, string> dictionary = new Dictionary<int, string>();
dictionary.Add(new KeyValuePair<int,string>(0,"0"));
dictionary.Add(new KeyValuePair<int,string>(1,"1"));
Backup a minute...before going down the road of the oversight, you should establish whether creating a new KeyValuePair is really so inefficient.
First off, the Dictionary class is not internally implemented as a set of key/value pairs, but as a bunch of arrays. That aside, let's assume it was just a set of KeyValuePairs and look at efficiency.
The first thing to notice is that KeyValuePair is a structure. The real implication of that is that it has to be copied from the stack to the heap in order to be passed as a method parameter. When the KeyValuePair is added to the dictionary, it would have to be copied a second time to ensure value type semantics.
In order to pass the Key and Value as parameters, each parameter may be either a value type or a reference type. If they are value types, the performance will be very similar to the KeyValuePair route. If they are reference types, this can actually be a faster implementation since only the address needs to be passed around and very little copying has to be done. In both the best case and worst case, this option is marginally better than the KeyValuePair option due to the increased overhead of the KeyValuePair struct itself.
There is such a method – ICollection<KeyValuePair<K, T>>.Add but as it is explicitly implemented you need to cast your dictionary object to that interface to access it.
((ICollection<KeyValuePair<KeyType, ValueType>>)myDict).Add(myPair);
See
List of Explicit Interface Implementations on Dictionary<K, T>'s documentation page (you'll need to scroll down).
Explicit member implementation
The page on this method includes an example.
Should somebody really want to do this, here is an Extension
public static void Add<T, U>(this IDictionary<T, U> dic, KeyValuePair<T, U> KVP)
{
dic.Add(KVP.Key, KVP.Value);
}
but i would recommend to not do this if there is no real need to do this
Unless I'm mistaken, .NET 4.5 and 4.6 adds the ability to add a KeyValuePair to a Dictionary. (If I'm wrong, just notify me and I'll delete this answer.)
https://msdn.microsoft.com/en-us/library/cc673027%28v=vs.110%29.aspx
From the above link, the relevant piece of information is this code example:
public static void Main()
{
// Create a new dictionary of strings, with string keys, and
// access it through the generic ICollection interface. The
// generic ICollection interface views the dictionary as a
// collection of KeyValuePair objects with the same type
// arguments as the dictionary.
//
ICollection<KeyValuePair<String, String>> openWith =
new Dictionary<String, String>();
// Add some elements to the dictionary. When elements are
// added through the ICollection<T> interface, the keys
// and values must be wrapped in KeyValuePair objects.
//
openWith.Add(new KeyValuePair<String,String>("txt", "notepad.exe"));
openWith.Add(new KeyValuePair<String,String>("bmp", "paint.exe"));
openWith.Add(new KeyValuePair<String,String>("dib", "paint.exe"));
openWith.Add(new KeyValuePair<String,String>("rtf", "wordpad.exe"));
...
}
As can be seen, a new object of type Dictionary is created and called openWith. Then a new KVP object is created and added to openWith using the .Add method.
just because the enumerator for the Dictionary class returns a KeyValuePair, does not mean that is how it is implemented internally.
use IDictionary if you really need to pass KVP's because you've already got them in that format. otherwise use assignment or just use the Add method.
What would be wrong with just adding it into your project as an extension?
namespace System.Collection.Generic
{
public static class DictionaryExtensions
{
public static void AddKeyValuePair<K,V>(this IDictionary<K, V> me, KeyValuePair<K, V> other)
{
me.Add(other.Key, other.Value);
}
}
}
I'm not 100% sure, but I think the internal implementation of a Dictionary is a Hash-table, which means key's are converted to hashes to perform quick look ups.
Have a read here if you want to know more about hashtables
http://en.wikipedia.org/wiki/Hash_table
In my solution i depend heavily on Dictionaries with an enum as a key. I find it is easy to understand and to read this construction.
One significant obstacle to the above is that it is not possible to serialize this. See Problems with Json Serialize Dictionary<Enum, Int32> for more info on this.
My question is:
Is there a equally readable and intuitive pattern for replacing the Dictionary<enunm,object> that is json serializable with the built in json serializer?
Today I have replaced a.Instance.QueryableFields[Fields.Title] with a.Instance.QueryableFields[ Fields.Title.ToString()] . Not very elegant, and it is opening up for errors.
When serializing it, just select the string value. It's not very neat, but it works.
a.Instance.QueryableFields.ToDictionary(x => x.Key.ToString(), x => x.Value)
You can easily replace a dictionary with an array here, as in C# Enums are internally saved as integers:
public enum MyEnum { Zero=0, One, Two };
object[] dictionary = new object[3];
dictionary[(int)MyEnum.Zero] = 4;
EDIT: (see comments)
You can also replace Dictionary<Enum, Object> with Dictionary<Int, Object>.
I have:
IDictionary<string, IDictionary<string, IList<long>>> OldDic1;
(just for illustration purposes, it is instantiated and has values - somewhere else)
Why can I do this: ?
Dictionary<string, IDictionary<string, IList<long>>> dic1 =
OldDic1 as Dictionary<string, IDictionary<string, IList<long>>>;
Basically dic1 after executing this line has all the values from OldDic1; works.
However when I do this:
Dictionary<string, Dictionary<string, List<long>>> dic1 =
OldDic1 as Dictionary<string, Dictionary<string, List<long>>>;
I get null, it is the same as casting except it doesn't crash and instead it returns null. So the question is why I can't cast it from the interfaces to types? is there solution, other then changing how it is stored in the first place?
You can only re-cast the outermost interface/class name, not the generic parameters. The reason your second cast doesn't work is the same reason you can't cast from one array type to another even if you can cast the "contained" objects. Here's why:
List<object> objects;
List<string> strings;
objects = strings as List<object>;
// Uh oh, that's not a string!
objects.Add(42);
objects = new List<object> { "The", "answer", "is", 42 };
// Uh oh, now strings contains an integer?
strings = objects as List<string>;
The same thing would happen in your second case. You could add some kind of IDictionary to OldDic1 which is not actually a Dictionary, and then dic1 would blow up. It would have a non-Dictionary value. Ruh roh!
So, when you have containers you can change from IList<X> to List<X> and back as long as X is identical for each.
The behavior is related to the as keyword in C#. A Dictionary is not the same thing as an IDictionary.
If you were casting the other way, you may be able to get it to work in the next version of .NET which has increased support for covariance and contravariance.
The solution you might want to determine why you need to cast to the concrete Dictionary/List, and if it's required, then change the storage of the type.
I have a generic dictionary, with an enumeration as its key and an int as its value.
I can't use an indexer on this (error is cannot apply indexer).
How could I write a custom indexer to enable this functionality?
Thanks
Could you do this?
Dictionary<YourEnum, int> dic = new Dictionary<YourEnum, int>();
dic.ElementAt(index);
But If I am not understanding the question can you specify a little more...