I have a list of objects. These objects have many properties including price and quantity. I need to create a new dictionary with key 'price' and value 'quantity'. If two objects have the same price, then the resulting dictionary should have the price as key and the sum of the quantities of both objects as value. As per my knowledge, I can do this in two ways.
- Using
Dictionarydata structure, and sort the final dictionary:
var result = new Dictionary<int, int>();
foreach(List<object> obj in list) {
if(result.ContainsKey(obj.price)) {
result[price] += quantity;
}
else {
result[price] = quantity;
}
}
result = result.OrderBy(x => x.Key);
- Using
SortedDictionary:
var result = new SortedDictionary<int, int>();
foreach(List<object> obj in list) {
if(result.ContainsKey(obj.price)) {
result[price] += quantity;
}
else {
result[price] = quantity;
}
}
In the first method, the time complexity for ContainsKey is O(1) and for sorting, order by uses quicksort which has time complexity O(nlogn). So the total time complexity would be O(nlogn). In the second method, the ContainsKey of sortedDictionary already takes O(log n) and as I am repeating this for n times, the total complexity would be O(nlogn). As per my calculation, I feel using both methods should take the same time. Please correct me if I'm wrong. And, if I'm wrong, which method has better performance?