C#语法 - 字符串分割到用逗号阵列,转换为通用名单,并反向订购 [英] C# Syntax - Split String into Array by Comma, Convert To Generic List, and Reverse Order
问题描述
什么是这个正确的语法:
What is the correct syntax for this:
IList<string> names = "Tom,Scott,Bob".Split(',').ToList<string>().Reverse();
什么我搞乱? ?
是什么TSource意味着
What am I messing up? What does TSource mean?
推荐答案
现在的问题是,我们在调用列表< T> .Reverse()
返回无效
The problem is that you're calling List<T>.Reverse()
which returns void
.
您既可以做:
List<string> names = "Tom,Scott,Bob".Split(',').ToList<string>();
names.Reverse();
或
IList<string> names = "Tom,Scott,Bob".Split(',').Reverse().ToList<string>();
后者更昂贵,倒车任意的IEnumerable< T>
涉及缓冲的所有数据,然后高产这一切 - 而列表< T>
可以完成所有的逆转就地。 (这里的区别在于,它调用了 Enumerable.Reverse< T>()
扩展方法,而不是列表< T> .Reverse()
实例方法)
The latter is more expensive, as reversing an arbitrary IEnumerable<T>
involves buffering all of the data and then yielding it all - whereas List<T>
can do all the reversing "in-place". (The difference here is that it's calling the Enumerable.Reverse<T>()
extension method, instead of the List<T>.Reverse()
instance method.)
更有效的是,你可以使用:
More efficient yet, you could use:
string[] namesArray = "Tom,Scott,Bob".Split(',');
List<string> namesList = new List<string>(namesArray.Length);
namesList.AddRange(namesArray);
namesList.Reverse();
这避免创建一个不恰当的大小的缓冲区 - 在服用四个语句,其中一个会做成本......与以往一样,重达可读性与性能在实际使用案例。
This avoids creating any buffers of an inappropriate size - at the cost of taking four statements where one will do... As ever, weigh up readability against performance in the real use case.
这篇关于C#语法 - 字符串分割到用逗号阵列,转换为通用名单,并反向订购的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!