Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient collection for accessing an object based on two key variants?

Tags:

c#

.net

I'm trying to implement a large cache of objects (up to 500000) and need to be able to access them in two different ways...

The key for each item is made up of three different strings; ItemNumber, PubCode and SizeCode. In some circumstances I'll be calling for a match on all three of those values to return a single object. In other cirumstances I'll be calling for a match on only ItemNumber and PubCode with a view to returning a collection of objects.

What is the best collection to use for this?

I've considered just using a generic list of object (of which all three of the key values are properties of) and using LINQ to query it, however I don't believe this is going to be the most performant way of doing this especially when you consider the size of the collection.

Any help will as always be appreciated!

like image 235
James Law Avatar asked Oct 03 '11 12:10

James Law


People also ask

Which collection is faster in c#?

ListDictionary is faster than Hashtable for small collections (10 items or fewer). The Dictionary<TKey,TValue> generic class provides faster lookup than the SortedDictionary<TKey,TValue> generic class.

How do I return a collection in C#?

To return a collection with repeated elements in C#, use Enumerable. Repeat method. It is part of System. Linq namespace.

Can we store different data types in list in C#?

We can use an ArrayList class that is present in the System. Collections namespace,. Using it we can store different types because the ArrayList class operates on the object type.


1 Answers

How many items are you likely to have for any ItemNumber / PubCode combination? If the answer is "reasonably few" then I would start off with a Lookup<ItemNumberPubCode, Value> (or a Dictionary<ItemNumberPubCode, List<Value>>) - so if you're asked to look up by just the two of them, you can get straight to all matches. If you're asked to look up by all three, you fetch all the matches of the first two really quickly, and then do an O(n) scan for any match by SizeCode.

(Here ItemNumberPubCode is a type encapsulating the ItemNumber and PubCode; this could be an anonymous type, a Tuple<string, string>, or a real type.)

If there can be lots of matches for a particular ItemNumber / PubCode combination, then you might want a Dictionary<ItemNumberPubCode, Dictionary<string, Value>> - that will let you efficiently search by all three, and from just two of them you can fetch the dictionaries and use the Values property to find all matching values for the pair.

like image 156
Jon Skeet Avatar answered Oct 19 '22 19:10

Jon Skeet