Sriram Subramanian
Sriram Subramanian

Reputation: 2753

Performance of Orderby Linq

I have a dictionary (string, UDT) where UDT is defined as

// simplified structure
class UDT
{
   public DateTime datetime;
   public double size;
};

I have to sort this dictionary by time and then by size very often. I am doing something like this now -

var result = dict.OrderBy(x => x.Value.datetime).ThenBy(x => x.Value.size);

foreach (KeyValuePair<string, UDT> val in result
{
}

The size of this dictionary is very large and most of the application bottleneck seems to be here. Is there any way to keep the dictionary sorted when items get added to the dictionary or to sort it more efficiently?

Upvotes: 2

Views: 2240

Answers (2)

M.Babcock
M.Babcock

Reputation: 18965

A more appropriate solution is to do what you're already doing by sorting when you read from the dictionary rather than keeping it sorted in memory. I would suggest caching the sorted result as a List though to reduce the amount of overhead.

Upvotes: 2

Joe
Joe

Reputation: 42607

If you have to repeatedly sort by the items in the value part of a IDictionary, you're doing it wrong, at least with large datasets.

Use a container that either allows you to store the data at insertion time in the correct order (e.g. SortedList, using a custom comparer) or a List that you then .Sort on an as-needed basis (again, with a custom comparer). It really depends on how often you are adding data and how often you need to re-sort. You'd have to measure for this.

Upvotes: 1

Related Questions