What is an alternative to Dictionaries in C# that allows for duplicate keys?
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;
}
There is an experimental NuGet package from MS that contains MultiValueDictionary
.
Basically, it's like Dictionary<Project, List<Technicians>>
, except that you don't have to repeat all the logic to manage the List
s every time you access it.