.NET / C# - Convert List to a SortedList

BuddyJoe picture BuddyJoe · Jun 11, 2009 · Viewed 27.4k times · Source

What is the best way to convert a List to SortedList? Any good way to do it without cycling through it? Any clever way to do it with an OrderBy()?

WRAP UP Please read all answers and comments.

Answer

ShuggyCoUk picture ShuggyCoUk · Jun 11, 2009

Do you mean:

  1. you have a List<T> and wish it to be sorted in place?
  2. you have a List<T> and wish to create another 'list' which is itself sorted
  3. you have a List<T> and wish to make a SortedList<T,T> where the key is the same as the value

Assuming input:

var x = new List<int>() { 3, 2, 1 };    

1 is trivial

x.Sort();

2 is trivial

// sx is an IOrderedEnumerable<T>, you can call ToList() on it if you want
var sx = x.OrderBy(i => i); 

3 is trivial with a copy

var s = new SortedList<int,int>(t.ToDictionary(i => i));

and more efficiently:

var s = new SortedList<int,int>();
foreach (var i in x) { s[i] = [i]; }

I can't see why you would want to do 3 but there you go.