A quick example:
Tom, Mary and John say "I want an apple"
Tom and John say "I want a race car"
John and Mary say "I want a pretty dress."
DataStructure[Tom] returns --> "I want an apple";"I want a racecar";
DataStructure[Mary] returns --> "I want an apple";"I want a pretty dress";
What is the idea data structure? If the number of keys or values can change? Where I could presumably type DataStructure.Add(Mary, “New String); or DataStructure.AddWithNewKey(“Timmy”, List)?
Is there a better way than keeping a list or array of strings for each person?
In the comments below, I was confused as to why it would matter if the data was known at compile time or was purely dynamic. Jon has pointed out that if the data was to be built dynamically, the ideal would be a dictionary related the string values to the people. Otherwise his linq solution is quite nice.
It sounds like you want an
ILookup– a map from keys to multiple values. You can create this using theToLookupmethod in LINQ. Alternatively, if you want to build something similar up in a mutable fashion, you can use aDictionary<,>where the type of the value is a list of some kind, e.g.Dictionary<string, IList<string>>. This is just a bit more fiddly than using a lookup, and doesn’t behave as elegantly for missing keys.The best solution will partly depend on how you’re getting your data, mind you. It’s not really clear from your example.
EDIT: You wouldn’t want a
Lookup<bool, StringInfo>. You’d want aLookup<Person, string>wherePersonwas an enum ofTom,Mary,Johnor something similar. The fact that these are hard-coded as properties is awkward, but not insurmountable. I would add a utility method like this:You can then use:
Then: