473,383 Members | 1,717 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

Using collections as key in Dictionary<TKey, TValue>

Hello, I am creating a program that has a byte[] used as the key for a Dictionary class. The problem is best described with an example:

(C# example of problem)
Expand|Select|Wrap|Line Numbers
  1.         private Dictionary<byte[], string> dictionary;
  2.  
  3.         public void Method1()
  4.         {
  5.             // Set up the dictionary
  6.             dictionary = new Dictionary<byte[], string>();
  7.             byte[] bytes1 = new byte[2] { 0, 0 };
  8.             byte[] bytes2 = new byte[2] { 0, 0 };
  9.             dictionary.Add(bytes1, "hello");
  10.  
  11.             // Search with byte[] 1, the original byte[]
  12.             string result1 = dictionary[bytes1];
  13.             string result2 = getMethod(bytes1);
  14.  
  15.             // Search with byte[] 2, the non-original one
  16.             // These throw errors specifying that the entry does not exist
  17.             string result3 = dictionary[bytes2];
  18.             string result4 = getMethod(bytes2);
  19.         }
  20.  
  21.         private string getMethod(byte[] getBytes)
  22.         {
  23.             return dictionary[getBytes];
  24.         }
I imagine the Dictionary is searching for the exact reference to the byte[] which was added to the Dictionary, and not just searching for a value match (which is what I want to do).

Thanks
Mar 31 '10 #1

✓ answered by clehene

@whosaidwhat, you need to supply a comparer to the Dictionary constructor.

http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

It's recommended that you extend EqualityComparer rather than implement the IEqualityComparer interface.

Basically you need to override the Equals and GetHashCode methods.

Here's an example of IEqualityComparer<byte[]>
http://www.christian-etter.de/?tag=iequalitycomparer

9 6641
tlhintoq
3,525 Expert 2GB
You haven't actually mentioned or described a problem: Only what you are doing? What is it that you need help with?
Mar 31 '10 #2
I want the Dictionary to be able to search for the key byte[] by the values contained in it. I want bytes2 array (used in my provided example) to match a entry in the Dictionary because its values are contained in a key in the Dictionary.
Mar 31 '10 #3
tlhintoq
3,525 Expert 2GB
I got the 'want' part.
What is actually happening? I can guess that it is in *some way* not described not working. But what is it doing?

I shouldn't have to feel like I'm interegating someone to try to help them. Try volunteering a full description of the problem, the expected behavior versus the actual behavior...

When you go to the doctor do yo say "I want to be able to walk, you figure the rest out." Or do you say "Every time I step the the left foot there is a shooting pain up the calf."
Mar 31 '10 #4
I do apologize I am having difficulty desribing the problem from a third party point of view and I am assuming too much.

Referring to the example provided:

Actual result: "string result3 = dictionary[bytes2];" Throws an error, saying it cannot find the entry.

Expected result: "string result3 = dictionary[bytes2]; " Returns "hello" and puts it into result3, this is what I want it to do.
Mar 31 '10 #5
tlhintoq
3,525 Expert 2GB
The problem is with the way you are trying to get the value from a dictionary like it was a simple array.
Expand|Select|Wrap|Line Numbers
  1. string result1 = dictionary[bytes1];
If bytes1 has a value of 5 then dictionary[5] would be the 6th key/value pair entry of the dictionary. There is no 'searching' taking place in what you are trying to do.

You need to supply the key you are looking for and a string to use as the 'out' variable for the matching value, if one is found
Expand|Select|Wrap|Line Numbers
  1. string value = "";
  2.         if (openWith.TryGetValue("tif", out value))
  3.         {
  4.             Console.WriteLine("For key = \"tif\", value = {0}.", value);
  5.         }
You should read up on the Dictionary on MSDN to see how to get values returned from the keys you are searching for.
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx
Apr 1 '10 #6
How I am trying to get values from the Dictionary by way of dictionary[KEY] is correct and works. In your example and the examples from MSDN the TKey is a string, or some other non-collection type. With my example the TKey is a byte array, this is what is required in my actual application.

As I have tried to show in my first example, I can retrive the value for an entry easily when I specify the exact byte[] that I added to the dictionary. If I create the another byte[] with the exact same data, it will not retrive any value.

I have limited experience in C++ but the problem I am having in C# seems to make more sense in C++. It is like I am telling the Dictionary to store a reference to the byte[] when I add an entry. So when the Dictionary tried to match a TKey (byte[]) with a value, it tries to find the key which matches the specified reference value, rather than matching the contents at the references address.

This problem only seems to occur when the Key is a collection type, I have tried substituting the byte[] for a List<byte>
Apr 1 '10 #7
tlhintoq
3,525 Expert 2GB
You may have hit on a bug/limitation of the Dictionary. are your bytes within the acceptable range of ASCII? You could store an ASCII representation of your byte[] IE. a string. It would mean just a little more coding to take your byte array into a string to put it in the dictionary then again when you pull it out.
Apr 1 '10 #8
@whosaidwhat, you need to supply a comparer to the Dictionary constructor.

http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

It's recommended that you extend EqualityComparer rather than implement the IEqualityComparer interface.

Basically you need to override the Equals and GetHashCode methods.

Here's an example of IEqualityComparer<byte[]>
http://www.christian-etter.de/?tag=iequalitycomparer
Jun 3 '10 #9
Plater
7,872 Expert 4TB
Yes, using a non base Type (things like ints, doubles, strings will work fine) make the dictionary look for the exact instance of the key, not a key with the same "value"

Following clehene's advice should get you what you need
Jun 3 '10 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

12
by: Brett Romero | last post by:
If I want to take action on the Add event of a generic Dictionary, do I need to create a custom Dictionary and add an event handler for the Add() method? The dictionary is a public field on a...
2
by: Shimon Sim | last post by:
I have Dictionary that has custom class as its key. For that class I implemented both Equals(object) and IComparable<T>. I keep getting KeyNotFoudException. What should I do? Thanks Shimon
7
by: Russell Hind | last post by:
I want to create an array of key value pairs. This code compiles fine: KeyValuePair<string, object> kvps = { new KeyValuePair<string,object>( "int", 5 ), new KeyValuePair<string,object>(...
6
by: buzzweetman | last post by:
Many times I have a Dictionary<string, SomeTypeand need to get the list of keys out of it as a List<string>, to pass to a another method that expects a List<string>. I often do the following: ...
7
by: bonk | last post by:
Hello I am acessing a Dictionary<TKey,TValuefrom multiple threads and often in a foreach loop. While I am within one of the foreach loops the other threads must not modify the collection itself...
10
by: Chris Mullins [MVP] | last post by:
KeyedCollection is a very handy little class, that unforutnatly has a nasty bug in it. The bug (which I ran across) causes the following code to fail: if (!rooms.Contains(room))...
44
by: Zytan | last post by:
The docs for List say "The List class is the generic equivalent of the ArrayList class." Since List<is strongly typed, and ArrayList has no type (is that called weakly typed?), I would assume...
4
by: Peter K | last post by:
Hi are there any benefits in using StringDictionary over Dictionary<string, string? It appears they achieve the same thing... (I could be wrong of course). thanks, Peter
6
by: daohuy.hua | last post by:
The context is that I have a C# class named MainModel which has a private Dictionary<string, FileStreammember named dict. I also have a property Dict to access to this member: public...
2
by: Dave | last post by:
I seem to be missing one of my favorite STL techniques for key, value collections - being able to use Composite Keys. What i mean by C.K. is the ability for a key to compare multiple values when...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.