The problem that I often encounter is the need to store a collection of objects so that I can get them by a specific field / property, which is a unique "index" for this object. For example, I have a Person object for which the name field is a unique identifier, and I want to be able to retrieve from some collection of Person objects on Person whose name="Sax Russell" . In Java, I usually do this with Map where I actually want Set , and always use the "index" field of the object as its key on the map, i.e. peopleMap.add(myPerson.getName(), myPerson) . I was thinking of doing the same in C # with Dictionary s, for example:
class Person { public string Name {get; set;} public int Age {get; set;}
However, this seems awkward and represents a rather weak connection between the Dictionary keys and its values; I am implicitly dependent on each Person dictionary producer using the Name property as the key to store each Person . I have no guarantee that the element in people["Sax Russell"] is actually a Person with Name="Sax Russell" if I do not double-check every time I access the dictionary.
Could there be some way to explicitly ensure that my collection of Person objects is indexed by name using custom equality comparisons and / or LINQ queries? It is important that the search remains constant, so I cannot just use List.Find or Enumerable.Where . I tried using a HashSet and creating it using an equality comparator, which compares only the Name field of the objects it gave, but there seems to be no way to then retrieve Person objects using only their name.
source share