编辑: 一个普通的(无序的)集合,例如HashSet<T> 以没有特定的顺序管理它的元素。因此,无序集合中特定元素的索引没有任何特定含义。
然而,相比之下,通过 SortedSet<T> 中的位置(索引)请求元素在语义上是有意义的。否则,何必为有序集合的开销而烦恼呢?
也就是说,对于不关心性能的小型SortedSet<T>(参见下面的示例),Linq 扩展方法Enumerable.ElementAt() 提供了一种通过索引检索项目的便捷方法。但是,对于检索元素的运行时性能至关重要的大型 SortedSet<T>,请考虑按照 his answer 中的 @Nicholas Carey 大纲实现自定义集合。
原答案:
您可以通过Enumerable.ElementAt<TSource> 方法通过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'!