简体   繁体   中英

unique key value collection in C#

I want to build 2-dimentional collection where i need unique combination of key value pairs. For example Domain "Company" (Id: 1) can have MachineName "Machine1" and "Machine2", but cannot add another MachineName "Machine1" again. Another Domain "Corporate" (Id:2) can have another machineName "Machine1".

here my collection will be like this 1-Machine1, 1-Machine2, 2-Machine1. Adding 1-Machine1 or 2-Machine1 should be invalid entry. Please suggest datatype or approach for this. I cannot use Dict> datatype, because it may hamper performance if size grows.

I'm sorry, but from your description it still sounds like a Dictionary implementation would be a good fit.

If and when the performance of the application suffers due to the speed of the dictionary, then you can revisit the problem and roll your own specifically tailored solution.

You could do something like this:

Dictionary<String, List<String>> mapping = new Dictionary<string, List<string>>();
mapping.Add("1",new List<string>());
mapping["1"].Add("Machine1");
mapping["1"].Add("Machine2");

This will give you a one to many mapping between domain and machines.

or the NameValueCollection class would do the same.

So you need some kind of collection with a unique key, and each item within this collection is unique.

So really, you're talking about a dictionary where the value within the dictionary is a unique collection.

Assuming you're only talking about strings, I'd be using something like:

Dictionary<string, HashSet<string>>

Someone correct me if I'm wrong, but I think the advantage of using these generic structures is you can (right off the bat), do this:

Dictionary<string, HashSet<string>> domains = new Dictionary<string, HashSet<string>>();
domains["Domain1"].Add("Machine1");

Do you need to be able to look up the list of domains with given machine name efficiently? Otherwise a Hashtable<String, HashSet<String>> seems like a good fit.

There also seems to be something called NameValueCollection which might be a good fit if you change the defaults so that it isn't case- or culture-sensitive.

You didn't state this as a requirement, but my guess is that you also need to be able to query the data structure for all of the machines for a specific "domain". Ex. list the machines belonging to Company 1. This is the only reason I can think of where the performance of using a Dictionary might be unacceptable (since you would have to traverse the entire list to find all of the matching entries).

In that case you might consider representing the data as a tree.

Edit:

Based on your comment above, you could just concatenate your keys as a string and use a HashSet to check if you've already stored that key.

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