我需要一个通用容器来保持其元素排序,并且可以询问它将插入新元素的位置(在哪个位置),而不实际插入它. 这样的容器是否存在于.NET库中? 最好的例子是一个例子(容器按ASCII值对字符
这样的容器是否存在于.NET库中?
最好的例子是一个例子(容器按ASCII值对字符进行排序,假设unicode不存在):
sortedContainer.Add('d');
sortedContainer.Add('b');
sortedContainer.Add('g');
//container contains elements ordered like 'b' 'd' 'g'
//index --------------------------------> 0 1 2
sortedContainer.GetSortedIndex('a'); //returns 0
sortedContainer.GetSortedIndex('b'); //returns 0
sortedContainer.GetSortedIndex('c'); //returns 1
sortedContainer.GetSortedIndex('d'); //returns 1
sortedContainer.GetSortedIndex('e'); //returns 2
sortedContainer.GetSortedIndex('f'); //returns 2
sortedContainer.GetSortedIndex('g'); //returns 2
sortedContainer.GetSortedIndex('h'); //returns 3
[...]
搜索位置应该利用元素排序的事实.
如果您对List<T>进行排序然后使用
List<T>.BinarySearch,它将为您提供条目的索引(如果它存在),或者如果您插入然后排序,它将插入的位置的索引的按位补码.从那以后,您应该能够轻松地构建您的方法.
示例代码与您的示例匹配,但不符合结果 – 如果您查看示例,则只有3个条目,因此“h”返回4或“g”返回3没有意义.我希望这是你的例子稍微偏离,而不是我误解了问题:)注意排序不是自动的 – 你必须在调用GetSortedIndex之前显式排序列表.
using System;
using System.Collections.Generic;
static class Test
{
static int GetSortedIndex<T>(this List<T> list, T entry)
{
int index = list.BinarySearch(entry);
return index >= 0 ? index : ~index;
}
static void Main()
{
List<char> container = new List<char> { 'b', 'd', 'g' };
Console.WriteLine(container.GetSortedIndex('a'));
Console.WriteLine(container.GetSortedIndex('b'));
Console.WriteLine(container.GetSortedIndex('c'));
Console.WriteLine(container.GetSortedIndex('d'));
Console.WriteLine(container.GetSortedIndex('e'));
Console.WriteLine(container.GetSortedIndex('f'));
Console.WriteLine(container.GetSortedIndex('g'));
Console.WriteLine(container.GetSortedIndex('h'));
}
}
