I have a method that returns groups of technicians who have worked on certain projects, for example:
project 1 | John project 1 | Tim project 2 | John project 2 | Dave
I originally tried to create a Dictionary which is usually my go-to collection of key-value pairs, but in this case I am unable to use it because I can't have a duplicate key (the project). What is an alternative that I can use?
My only thought is to create a Dictionary<Project, List<Technicians>>
but is there something much easier?
In Hashtable, you can store key/value pairs of the same type or of the different type. In Dictionary, you can store key/value pairs of same type. In Hashtable, there is no need to specify the type of the key and value. In Dictionary, you must specify the type of key and value.
A HashSet, similar to a Dictionary, is a hash-based collection, so look ups are very fast with O(1). But unlike a dictionary, it doesn't store key/value pairs; it only stores values. So, every objects should be unique and this is determined by the value returned from the GetHashCode method.
The Find() method of the List class loops thru each object in the list until a match is found. So, if we want to look up a value using a key, then a dictionary is better for performance over the list. So, we need to use a dictionary when we know the collection will be primarily used for lookups.
Dictionary is a collection of keys and values in C#. Dictionary is included in the System. Collection.
In your case, the same key is related to multiple values, so standard dictionary is not suitable, as is. You can declare it like Dictionary<Key, List<Values>>
.
But, also, you can use:
Lookup class, which is
Represents a collection of keys each mapped to one or more values.
You need framework 3.5 and more, for this.
What you need is a relationship between a Project
and one or more Technicians:
public class Project { public ICollection<Technician> Technicians { get; set; } } var project = new Project(); project.Technicians = new List<Technician>() { new Technician(), new Technician() };
Your objects should mirror the relationships in real life.
As a side note, you might be interested in reading about Domain-driven design.
public void LoadTechnicians(Project project) { List<Technician> techs = new List<Technician>(); // query the database and map Technician objects // Set the "Technicians" property project.Technicians = techs; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With