简体   繁体   中英

What is the correct way of using a Dictionary in C#?

I have (lots of) objects Foo with an unique ID and want to store these in a Dictionary . The dictionary key in C# can be any primitive type or object. I could use the integer foo1.ID as key but also the object foo1 .

Which is the correct way of implementing that and is there a difference in performance using either the ID (an integer) or the object as key?

NB. The values in the dictionary are other (type of) of objects.

It depends on your use case. Assuming you want to look up objects given their key value you of course want the id to be the key. That you are asking this question makes me think maybe you don't want a dictionary at all - if you just need to keep a collection of items use a List<T> instead - dictionaries are for mapping a key (eg an id) to a value (eg a custom object).

How do you intend to search the dictionary? If you intend to search for items within the dictionary based purely on ID , then use that as the key. OTOH, if you're going to have an instance of a Foo , then make that the key.


Re: your edit - now we know that the Foo is either "the key" or "the object that provides the key value by accessing a property", then it seems simple to say, use a Dictionary<Foo,OtherClass> - assuming you've set up equality comparisons on Foo objects appropriately - why force every instance of lookup to know to extract a specific property from the Foo objects?

Whatever you use as a key has to be able to be compared. For primitive types, equality is defined generally as you would expect. For objects, you would be testing reference equality unless you define another way to compare the objects, which you can do by passing the appropriate type of IComparer in the Dictionary constructor.

In your case, however, keying to the int is likely to be simplest. You would gain no real benefit from using the object as its own key. You can create the dictionary simply by taking your collection of Foo objects and doing something like:

IDictionary<int, Foo> fooDictionary = fooCollection.ToDictionary(f => f.ID);

Searching the dictionary will be more efficient than simply searching the collection for the given ID each time in most cases.

Dictionaries are Key Value Pairs . Each Key should be Unique. The Compiler has to make sure the Keys are unique. By Giving the Key as an object instead of an integer, You are probably doing an overkill. The compiler has compare to check the whole object in the Key to make sure it is unique. So i would go for Integer Key if that help you to identify your record uniquely.

使用ID-如果您已经有了对象,那么查找对象也没有意义。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM