I'm searching for an easy way to make a (sorted) dictionary for the following data with c#.
Person:
ID | Name |
---|---|
n4 | Anne |
n2 | Ben |
n3 | Ben |
n1 | Cesar |
Order:
PersonID | Description |
---|---|
n4 | Salami |
n4 | Ananas |
n3 | Banana |
n2 | Apple |
n1 | Banana |
n1 | Cheese |
For each Person (ID is unique, Name not) I should have all the Orders. I have to display all the rows ordered by Person.Name, like:
- Anne: Salami, Ananas
- Ben: Apple
- Ben: Banana
- Cesar: Banana, Cheese
The Values of the dictionary are not the problem, but the Key. My first approach was to use the Person.ID as key:
Dictionary<string, Queue<Order>> lastOrders = new Dictionary<string, Queue<Order>>();
But then I have the problem, that the dicionary is not ordered (when I take a SortedDictionary it would only be ordered by ID instead of Name). That means in a foreach loop I have to get the Person.Name for each key and create a new ordered list (?) and use this in a new foreach loop.
Because I need the Person.ID (as unique identifier) and Person.Name (for sorting) another option could be:
SortedDictionary<KeyValuePair<string, string>, Queue<Order>> lastOrders;
I think the first string must be the unique ID and the second the Name? But then, the dictionary is ordered again first by the ID instead the Name?
Because the PersonIDs never change (it's not a good example above, the Persons are static, the number of Persons can not change when the application is running) and only the Values of the dictionary changes, I think it is better to use a sorted dictionary (or to sort it once) than to sort it before every use (display). Maybe I'm thinking too far. Do you have a better idea? Thanks.
CodePudding user response:
From comment:
var persons = new SortedDictionary<Person, Queue<Order>>(Comparer<Person>.Create((p1, p2) => p1.Name.CompareTo(p2.Name)));