访问'SortedSet'中指定索引处的项

时间:2013-12-19 21:11:27

标签: c# .net indexing position set

如何在SortedSet

中的指定索引(位置)访问该项目

SortedList不同,SortedSet不提供Item property

(另外,与SortedList不同,SortedSet强制其每个成员都是唯一的。也就是说,SortedSet保证包含重复项。 )

4 个答案:

答案 0 :(得分:14)

那是因为SortedSet has the semantics of a set而不是类似List的构造。因此,它没有实现IList(这使您能够通过Item属性按索引处理项目。)

如@DavidRR所述,您可以使用Linq扩展方法Enumerable.ElementAt()。但是,由于SortedSet的后备存储是红黑树 - 高度平衡的二叉树,通过ElementAt()索引访问元素涉及树步行 - O(N),最差案例和平均O(N / 2),以达到所需的项目。与遍历单链表以访问N th 项非常相似。

所以...对于大型套装,性能可能很差。

如果您想要的是一个提供类似数组语义的唯一集合,那么为什么不推出自己的IList<T>实现来强制实现唯一性,就像SorteSet<T>那样(忽略已经存在的元素的添加)在集体中)。使用List<T>作为后备存储。按排序顺序维护它,以便您可以使用二进制搜索来确定添加的元素是否已存在。或者,只需子类型List<T>并覆盖适当的方法以获得所需的语义。

答案 1 :(得分:2)

编辑:普通(无序)集合(例如HashSet<T>)无需特定顺序管理其元素。因此,无序集合中特定元素的索引不具有任何特定含义。

然而,相比之下,通过SortedSet<T>中的位置(索引)来请求元素具有语义意义。为什么还要为有序集合的开销烦恼呢?

也就是说,对于性能不受关注的小SortedSet<T>(参见下面的示例),Linq扩展方法Enumerable.ElementAt()提供了一种通过索引检索项目的便捷方法。但是,对于检索元素的运行时性能至关重要的大SortedSet<T>,请考虑在his answer中将自定义集合实现为 @Nicholas Carey 大纲。


原始答案:

您可以通过SortedSet方法通过var item = mySortedSet.ElementAt(index); 的索引(位置)访问感兴趣的项目:

using System;
using System.Collections.Generic;
using System.Linq;

class SortedSetDemo
{
    static void Main(string[] args)
    {
        var words = new string[]
            {"the", "quick", "brown", "fox", "jumps",
             "over", "the", "lazy", "dog"};

        // Create a sorted set.
        var wordSet = new SortedSet<string>();
        foreach (string word in words)
        {
            wordSet.Add(word);
        }

        // List the members of the sorted set.
        Console.WriteLine("Set items in sorted order:");
        int i = 0;
        foreach (string word in wordSet)
        {
            Console.WriteLine("{0}. {1}", i++, word);
        }

        // Access an item at a specified index (position).
        int index = 6;
        var member = wordSet.ElementAt(index);

        Console.WriteLine("\nThe item at index {0} is '{1}'!", index,
                          member);
    }
}

<强>演示:

The set items in sorted order is:
0. brown
1. dog
2. fox
3. jumps
4. lazy
5. over
6. quick
7. the

The item at position 6 is 'quick'!

预期输出:

{{1}}

答案 2 :(得分:0)

如果您打算将数据加载到集合中,然后访问集合,请使用HashSetImmutableSortedSet而不是SortedSet

将数据加载到HashSet中,然后调用ToImmutableSortedSet()转换为可以索引的不可变排序集。

答案 3 :(得分:0)

您可以使用MCollections进行插入,编辑,删除,搜索和索引查找。在O(Lg(N))时间内,它使用BST并在每个节点中存储子节点的数量以访问该项目。指定的索引