我正在尋找一種簡單的方法來使用 c# 為以下資料制作(排序)字典。
人:
| ID | 姓名 |
|---|---|
| n4 | 安妮 |
| n2 | 本 |
| n3 | 本 |
| n1 | 塞薩爾 |
命令:
| 人名 | 描述 |
|---|---|
| n4 | 薩拉米 |
| n4 | 鳳梨 |
| n3 | 香蕉 |
| n2 | 蘋果 |
| n1 | 香蕉 |
| n1 | 奶酪 |
對于每個人(ID 是唯一的,姓名不是),我應該擁有所有訂單。我必須顯示按 Person.Name 排序的所有行,例如:
- 安妮:意大利臘腸、鳳梨
- 本:蘋果
- 本:香蕉
- 凱撒:香蕉??、奶酪
字典的值不是問題,而是鍵。我的第一種方法是使用 Person.ID 作為鍵:
Dictionary<string, Queue<Order>> lastOrders = new Dictionary<string, Queue<Order>>();
但是后來我遇到了問題,字典沒有排序(當我使用 SortedDictionary 時,它只會按 ID 而不是名稱排序)。這意味著在 foreach 回圈中,我必須為每個鍵獲取 Person.Name 并創建一個新的有序串列 (?) 并在新的 foreach 回圈中使用它。
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.
uj5u.com熱心網友回復:
來自評論:
var persons = new SortedDictionary<Person, Queue<Order>>(Comparer<Person>.Create((p1, p2) => p1.Name.CompareTo(p2.Name)));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/330471.html
標籤:c# .net sorting dictionary key
下一篇:如何從字典中的串列中存盤多個值
