简体   繁体   中英

C# Bulk Add to a Sorted List

I am looking for the fastest and most efficient way to use a sorted list or array under 2 different conditions. I wanna have my cake and eat it too!
First, I need to bulk add several hundred key/value pairs (possibly as many as 20,000) to the list/array and then have them sorted by key. QuickSort is probably the best way to do it, figuring out the insertion point and shuffling items after every addition certainly is not.
Afterwards, I need to occasionally add key/value pairs to the list/array on an as-needed basis and have them inserted at the right spot. Re-running QuickSort after every insertion is probably not the best way to do it.
And of course the reason I want it sorted is to do quick B-Tree lookups to find the value based on the key.
[FYI: In one case, The key is a Guid and the value is a struct or simple class with a string (human-friendly name) and a pair of ints. In the other case, the string is the key. Unfortunately, the string/name is not guaranteed to be unique. Everything is held in RAM because speed and responsiveness to the user is crucial. All the initial data that is bulk added is generated by another app and I have no control over it.]
I have some ideas on how to write a helper class to do this, but I'd rather not reinvent the wheel. Yet I cannot figure out a way to do it with the built in list or collection classes. The SortedList class does not appear to have a bulk add, and the regular list or array classes (once sorted) don't have a way to insert by key.

Suggestions?

You should consider the use of a Dictionary instead of a List , so long as you will be searching for elements based only on the key and not the value. This is an O(1) operation when trying to get a value for a single key, as opposed to having to make many comparisons to find the same object in a list.

var dictionary = new Dictionary<string, string>
{
    {"e11a5c0e-58b4-4f3c-86b8-6a127fff6ee8", "A"},
    {"7c1fdecf-7f75-4538-8805-50a67652a5a3", "B"},
    {"fed8892c-bb18-4fe3-8e31-8e287afa9243", "C"}
};

if (dictionary.TryGetValue("fed8892c-bb18-4fe3-8e31-8e287afa9243", out var value))
{
    Console.WriteLine($"The value is: {value}");
}

Also, if you could avoid using a GUID and use a sequential int or long , you would be able to add to the end of the list, right? No matter how you go about it, when you use a GUID as your key you're always going to have to make a number of comparisons to insert and swap the other elements to keep the list sorted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM