简体   繁体   中英

Returning IEnumerable from an indexer, bad practice?

If I had a CarsDataStore representing a table something like:

Cars
--------------
Ford | Fiesta
Ford | Escort
Ford | Orion
Fiat | Uno
Fiat | Panda

Then I could do

IEnumerable<Cars> fords = CarsDataStore["Ford"];

Is this a bad idea? It's inconsistent with the other datastore objects in my api (which all have a single column PK indexer), and I'm guessing most people don't expect an indexer to return a collection in this situation.

Yes, i think it's a bad idea, specially, if it's inconsistent with the rest of the api. Consistency is a key thing and you should always strive to be consistent.

I wouldn't expect an indexer to return a collection but then the compiler would tell me that if I ran into any problems.

However I would personally implement something more along the lines of

IEnumerable<Cars> fords = CarsDataStore.GetCarsByType("Ford");

Change your primary data structure and your issue goes away (syntax probably isn't perfect):

Dictionary<string, List<string>> cars =
    new Dictionary<string, List<string>>();

cars.Add("Ford", { "Fiesta", "Escort", "Orion" });
cars.Add("Fiat", { "Uno", "Panda" });

IEnumerable<string> fordCars = cars["Ford"];

Of course, you would have to change string to Car , but the idea would be the same.

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