473,659 Members | 2,651 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 31652
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
2870
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
3034
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
1669
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
2218
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
14969
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
16662
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
2128
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
10699
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
2016
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
8339
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
8851
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
8751
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
8535
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
7360
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6181
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4176
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2757
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1739
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.