C# 您可以使用 LINQ 或 LAMBDA 表达式在一行中对字符串进行反向排序吗

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1152887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 09:28:51  来源:igfitidea点击:

Can you reverse order a string in one line with LINQ or a LAMBDA expression

c#linqstringlambda

提问by Student for Life

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.

并不是说我想实际使用它(出于多种原因),而是出于严格的好奇心,我想知道是否有一种方法可以在一行代码中使用 LINQ 和/或 LAMBDA 表达式对字符串进行反向排序,而不使用任何框架“反向”方法。

e.g.

例如

string value = "reverse me";
string reversedValue = (....);

and reversedValue will result in "em esrever"

和 reversedValue 将导致“em esrever”

EDITClearly an impractical problem/solution I know this, so don't worry it's strictly a curiosity question around the LINQ/LAMBDA construct.

编辑显然是一个不切实际的问题/解决方案我知道这一点,所以不要担心它严格来说是一个围绕 LINQ/LAMBDA 构造的好奇问题。

采纳答案by Mehrdad Afshari

I don't see a practical use for this but just for the sake of fun:

我认为这没有实际用途,只是为了好玩:

new string(Enumerable.Range(1, input.Length).Select(i => input[input.Length - i]).ToArray())

回答by Jon Skeet

Well, I can do it in one very long line, even without using LINQ or a lambda:

好吧,即使不使用 LINQ 或 lambda,我也可以在很长的一行中完成:

string original = "reverse me"; char[] chars = original.ToCharArray(); char[] reversed = new char[chars.Length]; for (int i=0; i < chars.Length; i++) reversed[chars.Length-i-1] = chars[i]; string reversedValue = new string(reversed);

(Dear potential editors: do notunwrap 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:

请注意,这根本不使用 LINQ。LINQ 的答案是:

string reverseValue = new string(original.Reverse().ToArray());

Avoiding using Reverse, but using OrderByDescending instead:

避免使用 Reverse,而是使用 OrderByDescending:

string reverseValue = new string(original.Select((c, index) => new { c, index })
                                         .OrderByDescending(x => x.index)
                                         .Select(x => x.c)
                                         .ToArray());

Blech. I like Mehrdad's answer though. Of course, all of these are far less efficient than the straightforward approach.

布莱克。不过,我喜欢 Mehrdad 的回答。当然,所有这些都远不如直截了当的方法有效。

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...

哦,他们也都错了。反转字符串比反转代码点的顺序更复杂。考虑组合字符、代理对等...

回答by Dejan Stani?

Variant with recursive lambda:

递归 lambda 的变体:

  var value = "reverse me";
  Func<String, String> f = null; f = s => s.Length == 1 ? s : f(s.Substring(1)) + s[0]; 
  var reverseValue = f(value);

LP, Dejan

LP, 德扬

回答by Joe Chung

var reversedValue = value.ToCharArray()
                         .Select(ch => ch.ToString())
                         .Aggregate<string>((xs, x) => x + xs);

回答by Ben Lings

You can use Aggregateto prepend each Charto the reversed string:

您可以使用Aggregate将每个前置Char到反向字符串:

 "reverse me".Aggregate("", (acc, c) => c + acc);

回答by shlomiw

new string(value.Reverse().ToArray())

回答by rsa

var reversedValue= "reverse me".Reverse().ToArray();

回答by The Void

In addition to one previous post here is a more performant solution.

除了之前的一篇文章外,这里还有一个更高效的解决方案。

var actual0 = "reverse me".Aggregate(new StringBuilder(), (x, y) => x.Insert(0, y)).ToString();

回答by Vishav Premlall

public static string Reverse(string word)
{
   int index = word.Length - 1;
   string reversal = "";

   //for each char in word
   for (int i = index; index >= 0; index--)
   {
       reversal = reversal + (word.Substring(index, 1));
       Console.WriteLine(reversal);
   }
   return reversal;
}

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.

非常简单。所以,从现在开始,我有一个反转字符串的方法,它不使用任何内置的 Reverse 函数。

So in your main method, just go,

所以在你的主要方法中,去吧,

Console.WriteLine(Reverse("Some word"));

Console.WriteLine(Reverse("Some word"));

Technically that's your one liner :P

从技术上讲,这是你的一个班轮:P

回答by Jeppe Stig Nielsen

If we need to support combining characters and surrogate pairs:

如果我们需要支持组合字符和代理对:

// This method tries to handle:
// (1) Combining characters
// These are two or more Unicode characters that are combined into one glyph.
// For example, try reversing "Not nai\u0308ve.". The diaresis (¨) should stay over the i, not move to the v.
// (2) Surrogate pairs
// These are Unicode characters whose code points exceed U+FFFF (so are not in "plane 0").
// To be represented with 16-bit 'char' values (which are really UTF-16 code units), one character needs *two* char values, a so-called surrogate pair.
// For example, try "The sphere \U0001D54A and the torus \U0001D54B.". The  and the  should be preserved, not corrupted.

var value = "reverse me"; // or "Not nai\u0308ve.", or "The sphere \U0001D54A and the torus \U0001D54B.". 

var list = new List<string>(value.Length);

var enumerator = StringInfo.GetTextElementEnumerator(value);
while (enumerator.MoveNext())
{
  list.Add(enumerator.GetTextElement());
}
list.Reverse();

var result = string.Concat(list);

Documentation: MSDN: System.Globalization.StringInfoClass

文档:MSDN:System.Globalization.StringInfo