简体   繁体   中英

difference between IEnumerable vs Dictionary C#

If you go to this link in stackoverflow . There is a question about converting an Ienrumerable to Dictionary. So my question is why would we need IEnumerable when we have the dictionary object?

Actually, i am trying to figure out what is the difference between them.

IEnumerable is an interface . An interface can not be instantiated by itself, but have to be instantiated as a class that implements the given interface.

Dictionary is a hash-map datastructure that implements the IEnumerable interface, hence it have all the methods and properties that the IEnumerable interface requires its implementations to have, making it possible to Enumerate the Dictionary structure.

In short: IEnumerable is an interface and Dictionary is a class implementing the interface.

well, the question you've linked is on the opposite question. how to convert from IEnumerable to a Dictionary . why will we convert the other way around? we will probably won't. but you can also ask why will someone convert a specific class to object?

the answer is the sometimes you want to have a variable/method parameter/ class member that can be one of many things: a dictionary or something else. for that you might use IEnumerable .

So my question is why would we need IEnumerable when we have the dictionary object?

The question you've referred is about opposite: creating Dictionary from IEnumerable . So you have IEnumerable and you'd like to have Dictionary .

It can be required when you have eg e List and you'd like to have quicker access to collection elements by one of the items property value.

And just to be sure, Dictionary<TKey, TValue> already implements IEnumerable<T> , so the conversion would not necessary in the opposite direction (unless you're trying to change the T ).

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