ceonikka
ceonikka

Reputation: 455

c# Lookup for a value in Dictionary of Dictionary

I am in process of implementing design where information is organized in following way:

I thought of coding it as:

// MasterDB :(0..m)SourceID -- 1..n ->  [CaseID, InfoObject]
//
private Dictionary<string, Dictionary<string, InfoObject>> MasterDB;

Class InfoObject
{
    string user;
}

This way addition and removal becomes very easy as they use SourceID and CaseID as key.

However lookup is little special. I want to lookup for a particular user (which is embedded inside the InfoObject).

How should I reorganize such that things become little efficient both for lookup and addition/removal?

UPDATE:

I tried a different approach using LINQ

var targetList = from entry in MasterDB                          
                 from entrytarget in entry.Value
                      where (entrytarget.Value.user == username)
                      select entrytarget.Value;

Minor issue is that the returned list is a IEnumerable list. Not sure if I can make LINQ output some other way.

Upvotes: 1

Views: 645

Answers (3)

Tipx
Tipx

Reputation: 7505

I would use a Dictionary<string, IList<InfoObject> since nothing guarantees a user can't have more than one SourceID/CaseID pair.

Whenever you insert something in your other dictionary, you also insert the same InfoObjects in that dictionary of IList. This way the InfoObject retrieved is the same object.

Upvotes: 0

Vlad
Vlad

Reputation: 35594

I would propose to maintain additionally another dictionary, mapping the user into the appropriate collection of all relevant SourceID/CaseID pairs.

Upvotes: 3

BrokenGlass
BrokenGlass

Reputation: 160882

you could just have a separate lookup for users:

Dictionary<string, InfoObject> userLookup;

This only of course if you want to optimize for lookup speed, the downside is that addition and removal you have to do now on two separate data structures which have to keep in sync.

Upvotes: 4

Related Questions