使用 LinkedList 值创建 SortedDictionary

Creating SortedDictionary with LinkedList value

我有一个名为 "OrderItem" 的 class 和 class 实例的列表。 现在我想创建一个 SortedDictionary,其键将是 LinkedList 的 class 属性和值之一,LinkedList 中的所有项目都将具有相同的键 属性。 我想写一个与此相同的代码:

SortedDictionary<Double, LinkedList<OrderItem>> UnitPriceIndex;
foreach (OrderItem item in Data) // Data = list with all the instances of " OrderItem "
{ 
    UnitPriceIndex.Add(item.UnitPrice, LinkedList.add(item) // all items in the list will have the same UnitPrice
}

我该怎么做?

您需要先确保密钥存在。如果没有,则创建它并分配一个新列表作为值。

然后您可以将当前项添加到LinkedList。例如:

var UnitPriceIndex = new SortedDictionary<double, LinkedList<OrderItem>>();

foreach (OrderItem item in Data)
{
    // Make sure the key exists. If it doesn't, add it 
    // along with a new LinkedList<OrderItem> as the value
    if (!UnitPriceIndex.ContainsKey(item.UnitPrice))
    {
        UnitPriceIndex.Add(item.UnitPrice, new LinkedList<OrderItem>());
    }

    UnitPriceIndex[item.UnitPrice].AddLast(item);
}