Converting IList<string> to List<string>() [duplicate]
Asked Answered
A

5

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?

Alfy answered 1/9, 2011 at 13:11 Comment(1)
Do you actually need to sort the list, or just iterate over it in a particular order?Pleochroism
T
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; // ...
Tsan answered 1/9, 2011 at 13:13 Comment(4)
Just because the given IList<T> isn't specifically a List<T>, doesn't mean you can't sort it. ReadOnlyCollection implements IList<T> but isn't a List<T>. You should still be able to make a copy of it and sort it. The second example you posted is wrong.Pleochroism
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 :)Tsan
How is not working in this kind of situation not wrong? The reason IList<T> presumably how the given IList<T> 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.Pleochroism
Your first example is exactly what I was after. ThanksAlfy
O
7
IList<string> someVariable = GetIList();
List<string> list = someVariable.OrderBy(x => x).ToList();
Omeromero answered 1/9, 2011 at 13:14 Comment(0)
V
6

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

var newList = myIList.ToList();
newList.Sort();
Vaunting answered 1/9, 2011 at 13:14 Comment(1)
I think you need to call .Cast<> before .ToListUneasy
I
2

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

IList<string> foo = .... ; // something
var result = foo.OrderBy(x => x);
Impart answered 1/9, 2011 at 13:16 Comment(0)
B
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();
Bummalo answered 1/9, 2011 at 13:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.