能否使用 LINQ 或 LAMBDA 表达式对一行中的字符串进行反向排序
并不是说我想实际使用它(出于多种原因),而是出于严格的好奇心,我想知道是否有一种方法可以在一行代码中使用 LINQ 和/或 LAMBDA 表达式来反转字符串的顺序。 /strong>,不使用任何框架“反向”方法。
例如
string value = "reverse me";
string reversedValue = (....);
,reverseValue 将导致“em esrever”
编辑 显然这是一个不切实际的问题/解决方案,我知道这一点,所以不用担心,这只是围绕 LINQ/LAMBDA 构造的好奇问题。
Not that I would want to use this practically (for many reasons) but out of strict curiousity I would like to know if there is a way to reverse order a string using LINQ and/or LAMBDA expressions in one line of code, without utilising any framework "Reverse" methods.
e.g.
string value = "reverse me";
string reversedValue = (....);
and reversedValue will result in "em esrever"
EDIT
Clearly an impractical problem/solution I know this, so don't worry it's strictly a curiosity question around the LINQ/LAMBDA construct.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
好吧,即使不使用 LINQ 或 lambda,我也可以在很长的一行中完成此操作:(
亲爱的潜在编辑:不要将其展开到多行中。重点是它是一行,根据上面的句子和问题。)
但是,如果我看到有人为此避免使用框架方法,我会质疑他们的理智。
请注意,这根本不使用 LINQ。 LINQ 的答案是:
避免使用 Reverse,而是使用 OrderByDescending 代替:
Blech。 不过我喜欢迈赫达德的回答。 当然,所有这些方法的效率都远低于直接方法。
哦,他们也都错了。 反转字符串比反转代码点的顺序更复杂。 考虑组合字符、代理对等......
Well, I can do it in one very long line, even without using LINQ or a lambda:
(Dear potential editors: do not unwrap this onto multiple lines. The whole point is that it's a single line, as per the sentence above it and the question.)
However, if I saw anyone avoiding using framework methods for the sake of it, I'd question their sanity.
Note that this doesn't use LINQ at all. A LINQ answer would be:
Avoiding using Reverse, but using OrderByDescending instead:
Blech. I like Mehrdad's answer though. Of course, all of these are far less efficient than the straightforward approach.
Oh, and they're all wrong, too. Reversing a string is more complex than reversing the order of the code points. Consider combining characters, surrogate pairs etc...
我认为这没有实际用途,只是为了好玩:
I don't see a practical use for this but just for the sake of fun:
具有递归 lambda 的变体:
LP,
德扬
Variant with recursive lambda:
LP,
Dejan
您可以使用
Aggregate
将每个Char
添加到反转字符串之前:You can use
Aggregate
to prepend eachChar
to the reversed string:除了之前的一篇文章之外,这里还有一个性能更高的解决方案。
In addition to one previous post here is a more performant solution.
非常简单。 因此,从现在开始,我有一个反转字符串的方法,该方法不使用任何内置的 Reverse 函数。
因此,在您的主要方法中,只需执行
Console.WriteLine(Reverse("Some word"));
从技术上讲,这就是您的单行代码:P
Quite simple. So, from this point on, I have a single method that reverses a string, that doesn't use any built-in Reverse functions.
So in your main method, just go,
Console.WriteLine(Reverse("Some word"));
Technically that's your one liner :P
如果我们需要支持组合字符和代理项对:
If we need to support combining characters and surrogate pairs:
Documentation: MSDN:
System.Globalization.StringInfo
Class