C# 语法 - 用逗号将字符串拆分为数组、转换为通用列表以及倒序
正确的语法是什么:
IList<string> names = "Tom,Scott,Bob".Split(',').ToList<string>().Reverse();
我搞砸了什么? TSource 是什么意思?
What is the correct syntax for this:
IList<string> names = "Tom,Scott,Bob".Split(',').ToList<string>().Reverse();
What am I messing up?
What does TSource mean?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
问题是您正在调用
List.Reverse()
,它返回void
。您可以这样做:
或:
后者成本更高,因为反转任意
IEnumerable
涉及缓冲所有数据,然后生成所有数据 - 而List
code> 可以“就地”完成所有反转。 (此处的区别在于,它调用Enumerable.Reverse()
扩展方法,而不是List.Reverse()
实例方法。)高效,您可以使用:
这可以避免创建任何大小不合适的缓冲区 - 代价是在一个可以做的地方采取四个语句...一如既往,在实际用例中权衡可读性与性能。
The problem is that you're calling
List<T>.Reverse()
which returnsvoid
.You could either do:
or:
The latter is more expensive, as reversing an arbitrary
IEnumerable<T>
involves buffering all of the data and then yielding it all - whereasList<T>
can do all the reversing "in-place". (The difference here is that it's calling theEnumerable.Reverse<T>()
extension method, instead of theList<T>.Reverse()
instance method.)More efficient yet, you could use:
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.
我意识到这个问题已经很老了,但我也有类似的问题,只是我的字符串中包含空格。 对于那些需要知道如何用逗号分隔字符串的人:
StringSplitOptions 删除仅是空格字符的记录...
I realize that this question is quite old, but I had a similar problem, except my string had spaces included in it. For those that need to know how to separate a string with more than just commas:
The StringSplitOptions removes the records that would only be a space char...
这个有效。
This one works.
尝试这个:
Try this:
您在这里缺少的是 .Reverse() 是一个 void 方法。 无法将 .Reverse() 的结果分配给变量。 但是,您可以更改使用 Enumerable.Reverse() 的顺序并获取结果。
不同之处在于 Enumerable.Reverse() 返回一个 IEnumerable。 而不是无效返回
What your missing here is that .Reverse() is a void method. It's not possible to assign the result of .Reverse() to a variable. You can however alter the order to use Enumerable.Reverse() and get your result
The difference is that Enumerable.Reverse() returns an IEnumerable<T> instead of being void return
如果您尝试
以下应该可以工作:
输出
您显然可以按照其他人的建议反转顺序。
If you are trying to
following should work:
Output
Now you can obviously reverse the order as others suggested.