Junior — Middle
What methods can be used to remove key restrictions in a dictionary data structure?
sobes.tech AI
Answer from AI
In C#, keys in a dictionary (Dictionary<TKey, TValue>) must be unique and immutable for correct hashing. To overcome key restrictions, the following approaches can be used:
-
Use a composite key — create a class or structure that combines multiple values, and override the
EqualsandGetHashCodemethods for proper comparison. -
Use a collection of values for a single key — for example,
Dictionary<TKey, List<TValue>>, to store multiple values under one key. -
Use
LookuporIGrouping— if you need to group data by key. -
Use
ConcurrentDictionaryor other specialized collections — if thread safety is required. -
Use
ImmutableDictionary— if an immutable collection is needed.
Example of a composite key:
class CompositeKey
{
public int Id { get; set; }
public string Name { get; set; }
public override bool Equals(object obj) => obj is CompositeKey other && Id == other.Id && Name == other.Name;
public override int GetHashCode() => HashCode.Combine(Id, Name);
}
var dict = new Dictionary<CompositeKey, string>();
dict[new CompositeKey { Id = 1, Name = "A" }] = "Value1";