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?
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?
you can just do
var list = new List<string>(myIList);
list.Sort();
or
var list = myIList as List<string>;
if (list != null) list.Sort; // ...
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 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 IList<string> someVariable = GetIList();
List<string> list = someVariable.OrderBy(x => x).ToList();
IList implements IEnumerable. Use the .ToList() method.
var newList = myIList.ToList();
newList.Sort();
.Cast<>
before .ToList
–
Uneasy You can use linq to sort an IList<string>
like so:
IList<string> foo = .... ; // something
var result = foo.OrderBy(x => x);
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();
© 2022 - 2024 — McMap. All rights reserved.