Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用LinkedList值创建SortedDictionary_C#_Sorteddictionary - Fatal编程技术网

C# 使用LinkedList值创建SortedDictionary

C# 使用LinkedList值创建SortedDictionary,c#,sorteddictionary,C#,Sorteddictionary,我有一个名为“OrderItem”的类和该类实例的列表。 现在我想创建一个SortedDictionary,它的键将是LinkedList的类属性和值之一,LinkedList中的所有项都将具有相同的键属性。 我想写一个与此相同的代码: SortedDictionary<Double, LinkedList<OrderItem>> UnitPriceIndex; foreach (OrderItem item in Data) // Data = list with al

我有一个名为“OrderItem”的类和该类实例的列表。 现在我想创建一个SortedDictionary,它的键将是LinkedList的类属性和值之一,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
}
SortedDictionary单价索引;
foreach(数据中的OrderItem)//Data=包含“OrderItem”所有实例的列表
{ 
UnitPriceIndex.Add(item.UnitPrice,LinkedList.Add(item)//列表中的所有项目都将具有相同的单价
}

如何操作?

您需要首先确保该键存在。如果不存在,则创建该键并指定一个新列表作为值

然后,您可以将当前项目添加到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);
}
var UnitPriceIndex=new SortedDictionary();
foreach(数据中的OrderItem)
{
//确保密钥存在。如果不存在,请添加它
//以及一个新的LinkedList作为值
如果(!UnitPriceIndex.ContainsKey(item.UnitPrice))
{
添加(item.UnitPrice,new LinkedList());
}
单价索引[项目.单价].AddLast(项目);
}

首先必须检查该项是否已存在于词典中。如果已存在,则将其添加到现有列表中,如果不存在,则添加新条目。