C# - custom type in a dictionary / key/value pair

xrapidx

Honorary Master
Joined
Feb 16, 2007
Messages
42,197
Reaction score
4,041
Location
Cape Town
Need a bit of help, I'd like to add a custom type to a dictionary or key/value pair. But - not coming right - and not an application developer.

Basically, I want a list/dictionary/array/whatever to store a simple collection of keys (always int) - and values (could be a single string, or a combination of strings, or a combination of strings and integers.

I'd then like to be able to search this collection as fast as possible by either the key - or the value collection.

I currently have the following (simplified), but would like to extend it to allow multiple values:

(ignore the layout as some of it is done in different sections of code)

Code:
List<KeyValuePair<int, string>> ListCache;
ListCache = new List<KeyValuePair<int, string>>();

<somewhere else in a class>

ListCache<int, string> record_found = ListCache.SingleOrDefault(x => x.Value == "incoming search term");

int outputKey = record_found .Key;

// if record not in list
if (outputKey == 0)
{
    // do some db stuff 

   ListCache.Add(new KeyValuePair<int, string>(newKey, "incoming search term"));

  outputKey = newKey;
}

return outputKey;

My ideal outcome would be to allow for

List<KeyValuePair<int, string>> ListCache;

to have a collection of Values that are also searchable, e.g.
List<KeyValuePair<int, [int, string]>> ListCache;
 
Look into Runtime.Caching, why reinvent the wheel.
 
Think I finally figured it out - haven't checked the above, but this is specific to code referenced in SQL Server, so not sure what's available.
 
Dictionary<int, object>?
Yeh, the issue I was having was searching for the object:
ListCache<int, string> record_found = ListCache.SingleOrDefault(x => x.Value == "incoming search term");
 
You’d need to know the type and cast it, so possibly something like: Dictionary<int, (Type, object)> - I.E store a tuple in the value (which holds the Type and the value)

If you want to search for a string with a value, then iterate the values of the dictionary, where “Type == typeOf(string) && string(obj) == “some string””

But this just seems dirty and possibly you need to reconsider your design/requirements
 
I created a type - so basically have:

ListCache<int, MySpecialType> record_found = ListCache.SingleOrDefault(x => x.Value == incomingspecialtype);

Where MySpecialType is a collection of various other types, e.g. strings, ints, what-ever is needed.

Not sure of the correct terminology - but it seems to work.
 
Top
Sign up to the MyBroadband newsletter
X