开发者

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

开发者 https://www.devze.com 2023-04-02 06:37 出处:网络
This question already has answers here: Cast IList to List (9 answers) Closed 9 years ago. I have a function that takes IList<string> someVariable as a parameter. I want to convert th
This question already has answers here: Cast IList to List (9 answers) Closed 9 years ago.

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();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号