views:

96

answers:

3

My need is to have items in kind of Collections.Generic.Dictionary where I can get a struct by it's id as a key. Then I have need to fetch many structs, say 1% or less of all items, by another field. Like a cursor by an non-unique index. With Dictionary I have to browse through all the values and check which has the correct value for that field. My question is: "What data structure should I use to support this kind of unique index and non-unique index behaviour found in RDBMSs?"

Thanks!

br: Matti

EDIT: VS 2005 and .NET 2.0

+1  A: 

One option, if performance is important, is to maintain a Dictionary of Lists. For example, suppose you had:

class Employee {
    int DeptID;   // A non-unique field we want to index on
    ...
}

Then:

Dictionary<int, LinkedList<Employee>> EmpsByDept; 

I'm using LinkedList here to get fastest insert/removal performance. You could use a List as well.

Tarydon
That's what I do too :)
leppie
thanks, but this does not support the unique key fetching. actually i might not need that at all but that's what i want at this point...
matti
@matti: For the unique key fetching, you would use another Dictionary.
Tarydon
A: 

I think you should use different collections for different needs. For example, you can incapsulate this logic into one class that contains several containers that optimized for specific needs:

class Key {}

class Value {}

class MySpecificStorage
{
    public void AddSomeEntry(Key key, Value value)
    {
        dictionary[key] = value;
        values.Add(value);
    }
    public Value FindValueByKey(Key key)
    {
        //very simple
        return dictionary[key];
    }
    public IEnumerable<Value> GetSomeRange()
    {
        //use LINQ or something else
        //to fetch many structs, say 1% or less of all items, by another field.
        //You can even use different Dictionaries for that
        return ...;
    }

    private Dictionary<Key, Value> dictionary = new Dictionary<Key, Value>();
    private List<Value> values = new List<Value>(); //or List<KeyValuePair<Key, Value>> values;

}
Sergey Teplyakov
+1  A: 

I don't believe there is a built in Dictionary like collection accepting non-unique TKey values, but you might be interested in the following project:

http://www.codeproject.com/KB/cs/Multi-Index_Container.aspx

elmar