EDIT: An ordinary (unordered) set such as HashSet<T> manages its elements in no particular order. So, the index of a particular element in an unordered set does not carry any particular meaning.
In contrast however, it makes semantic sense to request an element by its position (index) in a SortedSet<T>. Why bother with the overhead of an ordered collection, otherwise?
That said, for a small SortedSet<T> where performance is not a concern (see example below), the Linq extension method Enumerable.ElementAt() provides a convenient means of retrieving an item by its index. However, for a large SortedSet<T> where the runtime performance of retrieving an element is paramount, consider implementing a custom collection as @Nicholas Carey outlines in his answer.
Original Answer:
You can access an item of interest by its index (position) from your SortedSet
via the Enumerable.ElementAt<TSource>
method:
var item = mySortedSet.ElementAt(index);
Demonstration:
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);
}
}
Expected Output:
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'!