开发者

is there a .NET C# collection that supports fetch by both unique keys and non-unique fields?

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 inde开发者_JS百科x behaviour found in RDBMSs?"

Thanks!

br: Matti

EDIT: VS 2005 and .NET 2.0


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


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.


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;

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜