473,837 Members | 1,524 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# 2.0: Generic Dictionary - How to lookup a Value and return the key ?

Hi There

I am probably missing something fundamental here, but I cannot see a
method to search the values of a generic dictionary so that I can find
the key ? Of course I could enumerate through the Values collection
but that seems a little long winded.

I ended up using a sorted list because it has the IndexOfValue method.
However I don't need the sorting.

What am I missing ? fyi, the class is below

TIA
Bill

_______________ ______
public abstract class AusStates

{

static SortedList<char , string> stateListing = new SortedList<char ,
string>();

public AusStates()

{

stateListing.Ad d('2', "NSW");

stateListing.Ad d('3', "VIC");

stateListing.Ad d('4', "QLD");

stateListing.Ad d('5', "SA");

stateListing.Ad d('6', "WA");

stateListing.Ad d('7', "TAS");

stateListing.Ad d('A', "ACT");

stateListing.Ad d('0', "NT");

}

public static char GetStateChar(st ring itemToLookup)

{

int indexToFind =
stateListing.In dexOfValue(item ToLookup.Trim() .ToUpper(Cultur eInfo.CurrentCu lture));

if (indexToFind == -1)

return ' '; //Keep consistent with old design

else

return stateListing.Ke ys[indexToFind];

}

public static string GetStateTxt(cha r itemToLookup)

{

int indexToFind = stateListing.In dexOfKey(itemTo Lookup);

if (indexToFind == -1)

return " "; //Keep consistent with old design

else

return stateListing.Va lues[indexToFind];

}

}

Nov 17 '05 #1
2 31659
On 4 Aug 2005 21:30:09 -0700, or*******@yahoo .com.au wrote:
I am probably missing something fundamental here, but I cannot see a
method to search the values of a generic dictionary so that I can find
the key ? Of course I could enumerate through the Values collection
but that seems a little long winded.


You're not missing anything, and linear enumeration is indeed the only
way to find a value in a hashtable (which is what a Dictionary is).

Enumerating through the Values collection alone still won't help you
find the associated key, by the way -- you'll have to iterate through
the Dictionary itself:

TKey GetByValue(IDic tionary<TKey, TValue> dictionary, TValue value) {
if (dictionary == null)
throw new ArgumentNullExc eption("diction ary");

foreach (KeyValuePair<T Key, TValue> pair in dictionary)
if (value.Equals(p air.Value)) return pair.Key;

return default(TKey); // or throw exception
}

This will crash if value is null, by the way. You can't directly test
value for null in the July CTP due to a compiler bug. If you want to
allow null values you'll have to do a more elaborate value comparison.
--
http://www.kynosarges.de
Nov 17 '05 #2
>What am I missing ? fyi, the class is below

That multiple keys may have the same value? The method you suggest
would have to return all keys that have the given value (or perhaps
the first one found, but since a dictionary isn't ordered that may be
unpredictable).

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 17 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

49
2914
by: Steven Bethard | last post by:
I promised I'd put together a PEP for a 'generic object' data type for Python 2.5 that allows one to replace __getitem__ style access with dotted-attribute style access (without declaring another class). Any comments would be appreciated! Thanks! Steve ----------------------------------------------------------------------
18
3059
by: Steven Bethard | last post by:
In the "empty classes as c structs?" thread, we've been talking in some detail about my proposed "generic objects" PEP. Based on a number of suggestions, I'm thinking more and more that instead of a single collections type, I should be proposing a new "namespaces" module instead. Some of my reasons: (1) Namespace is feeling less and less like a collection to me. Even though it's still intended as a data-only structure, the use cases...
2
1677
by: John | last post by:
I am trying to design a dictionary in such a way that I can keep the interface and implementation separate. Here is my initial design. Anyone has any comments on it or suggestions on how I could make it better. Does anyone have a good code/pointer that discusses dictionary design. Thanks,
4
2226
by: Adam Clauss | last post by:
I ran into a problem a while back when attempting to convert existing .NET 1.1 based code to .NET 2.0 using Generic collections rather than Hashtable, ArrayList, etc. I ran into an issue because the old code allowed me to do what basically was the following assignment: class SomeClass { private Queue q; SomeClass(Queue q)
18
14980
by: Rune B | last post by:
Hi Group I was considering using a Generic Dictionary<> as a value container inside my business objects, for the reason of keeping track of fields changed or added and so on. - But how expensive is it to instantiate/use Generic Dictionaries in great numbers (let's just say 100000's ), in terms of memoryuse and performance? Any practical experiences out there?
7
16674
by: Sehboo | last post by:
We have several generic List objects in our project. Some of them have about 1000 items in them. Everytime we have to find something, we have to do a for loop. There is one method which does the searching, but that method receives the object, and the string to search in that object and runs the FOR loop to find the answer. This is taking time because we have to do searching hundres of times. I want to use Hashtable, but the problem...
4
2134
by: Ram | last post by:
Hi All, I am new to this Generics. I started with a Generic method which doesn't return any value. It worked well. Then I tried to write a generic method which will sum up the given values and return the result. This is the piece of code. private T Add<T>(T a, T b) {
2
10706
by: Stephen Costanzo | last post by:
I have: Public Class test Private displayValue As String Private dbType As Integer Property Display() As String Get Return displayValue End Get
3
2020
by: Phil Sandler | last post by:
All, I have a situation where I need a List<stringthat performs like a generic dictionary (Dictionary<string, string>). Essentially, I just need the key, not the value, so I want to use as little memory as possible. Currently I am setting all the values of the dictionary to null. The List<stringdoesn't work because I am doing a lot of .Contains() or .ContainsKey(), and lookup speed is pretty critical.
0
9843
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9682
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10881
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10575
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10628
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10275
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7004
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
4043
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3126
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.