Converting IList<string> to List<string>() [duplicate]
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<string> someVariable = GetIList();
List<string> list = someVariable.OrderBy(x => x).ToList();
IList implements IEnumerable. Use the .ToList() method.
var newList = myIList.ToList();
newList.Sort();
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();
精彩评论