我有一個像下面這樣類型的字典對象。使用C#對嵌套字典排序
Dictionary<string, Dictionary<Roles, Dictionary<Period, List<Product>>>>
的角色(是一個枚舉),有「編制者」 &「審批人」作爲自己的物品。同樣,Period是另一個具有「前」&「過去」項目的枚舉。
列表中包含各種產品的列表。
我在字典中有以下層次結構中的項目。
"Sachin" --> Roles.Preparer --> Period.Past --> Products
"Sachin" --> Roles.Approver --> Period.Ahead --> Products
"Sachin" --> Roles.Approver --> Period.Ahead --> Products
"Sachin" --> Roles.Approver --> Period.Past --> Products
我將不得不按以下順序對字典進行排序。
"Sachin" --> Roles.Preparer --> Period.Ahead --> Products
"Sachin" --> Roles.Approver --> Period.Ahead --> Products
"Sachin" --> Roles.Preparer --> Period.Past --> Products
"Sachin" --> Roles.Approver --> Period.Past --> Products
此結構是必需的,因爲我將不得不迭代通過每個項目,並應添加爲郵件的一部分。
實際的代碼是這樣的。
`using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Basics
{
class Product
{
public string Name { get; set; }
public int Days { get; set; }
}
enum Period
{
Ahead,
Past
}
enum Roles
{
Preparer,
Approver
}
class Program
{
static void Main(string[] args)
{
DictionaryProcessing(new string[] { "[email protected]", "[email protected]" });
}
private static void DictionaryProcessing(string[] emailIDs)
{
List<Product> products = new List<Product>();
Product product1 = new Product() { Name = "Pencil", Days = 14 };
Product product2 = new Product() { Name = "Eraser", Days = 2 };
Product product3 = new Product() { Name = "Geometry Box", Days = 31 };
products.Add(product1);
products.Add(product2);
products.Add(product3);
Dictionary<string, Dictionary<Roles, Dictionary<Period, List<Product>>>> dict = new Dictionary<string, Dictionary<Roles, Dictionary<Period, List<Product>>>>();
///
foreach (string emailID in emailIDs)
{
if (!dict.ContainsKey(emailID))
dict.Add(emailID, new Dictionary<Roles, Dictionary<Period, List<Product>>>());
if (!dict[emailID].ContainsKey(Roles.Preparer))
dict[emailID].Add(Roles.Preparer, new Dictionary<Period, List<Product>>());
if (!dict[emailID][Roles.Preparer].ContainsKey(Period.Ahead))
dict[emailID][Roles.Preparer].Add(Period.Ahead, new List<Product>());
if (!dict[emailID][Roles.Preparer].ContainsKey(Period.Past))
dict[emailID][Roles.Preparer].Add(Period.Past, new List<Product>());
///
if (!dict[emailID].ContainsKey(Roles.Approver))
dict[emailID].Add(Roles.Approver, new Dictionary<Period, List<Product>>());
if (!dict[emailID][Roles.Approver].ContainsKey(Period.Ahead))
dict[emailID][Roles.Approver].Add(Period.Ahead, new List<Product>());
if (!dict[emailID][Roles.Approver].ContainsKey(Period.Past))
dict[emailID][Roles.Approver].Add(Period.Past, new List<Product>());
for (int i = 0; i < products.Count; i++)
{
dict[emailID][Roles.Preparer][Period.Ahead].Add(products[i]);
dict[emailID][Roles.Preparer][Period.Past].Add(products[i]);
dict[emailID][Roles.Approver][Period.Past].Add(products[i]);
dict[emailID][Roles.Approver][Period.Ahead].Add(products[i]);
}
}
}
}
}
`
如何按此順序對其進行排序? 我僅限於使用.NET 2.0框架。
我堅信這將是更容易維護,如果您使用的是標準的DataTable代替嵌套字典的讀取。 –