简体   繁体   中英

c# Lookup for a value in Dictionary of Dictionary

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

  • Multiple sources will feed us with multiple case information.
  • Each source is identified by SourceID string and each case is idenfied by CaseID string.
  • The information packet will be encapsulated as InfoObject.

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.

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.

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

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 InfoObject s in that dictionary of IList. This way the InfoObject retrieved is the same object.

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