I have a class called "OrderItem" and a list of the class's instances. Now I want to create a SortedDictionary that the key would be one of the class properties and value of LinkedList that all of the items in the LinkedList will have the same key property. I want to write a code same as this:
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
}
How can I do it?
You need to make sure the key exists first. If it doesn't, then create it and assign a new list as value.
Then you can just add the current item to the LinkedList. For example:
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);
}