5

I have a function that takes IList<string> someVariable as a parameter. I want to convert this to a list so I can sort the values alphabetically.

How do I achieve this?

bluish
  • 26,356
  • 27
  • 122
  • 180
hoakey
  • 998
  • 3
  • 18
  • 34
  • 1
    Do you actually need to sort the list, or just iterate over it in a particular order? – Roman Sep 01 '11 at 13:23

5 Answers5

8

you can just do

var list = new List<string>(myIList);
list.Sort();

or

var list = myIList as List<string>;
if (list != null) list.Sort; // ...
Random Dev
  • 51,810
  • 9
  • 92
  • 119
  • Just because the given `IList` isn't specifically a `List`, doesn't mean you can't sort it. [`ReadOnlyCollection`](http://msdn.microsoft.com/en-us/library/ms132474.aspx) implements `IList` but isn't a `List`. You should still be able to make a copy of it and sort it. The second example you posted is wrong. – Roman Sep 01 '11 at 13:22
  • maybe I was not 100% clear in this - it's not wrong it's just not working in this kind of situations (Sort will just not be called) - but thank your for the hint - I guess there are enough examples here to pick one :) – Random Dev Sep 01 '11 at 13:33
  • How is *not working in this kind of situation* not wrong? The reason `IList` presumably **how** the given `IList` is implemented is an unimportant implementation detail that could change without warning. Your second example would silently start to fail. I'd say forcing an explicit dependency where there isn't one is **wrong**. – Roman Sep 01 '11 at 13:37
  • Your first example is exactly what I was after. Thanks – hoakey Sep 01 '11 at 14:07
7
IList<string> someVariable = GetIList();
List<string> list = someVariable.OrderBy(x => x).ToList();
Bala R
  • 107,317
  • 23
  • 199
  • 210
6

IList implements IEnumerable. Use the .ToList() method.

var newList = myIList.ToList();
newList.Sort();
John Kraft
  • 6,811
  • 4
  • 37
  • 53
2

You can use linq to sort an IList<string> like so:

IList<string> foo = .... ; // something
var result = foo.OrderBy(x => x);
recursive
  • 83,943
  • 34
  • 151
  • 241
2

You don't have to convert to a List to sort things. Does your sorting method require a List but not accept an IList. I would think this is the actual problem.

Furthermore if you really need a List, if your IList realy is a List (which is somewhat likely) you can just interpret it as such. So I would first check if it is already a List before creating a new one

var concreteList = parameter as List<T> ?? parameter.ToList();
chrisaut
  • 1,076
  • 6
  • 17