【问题标题】:How to convert an array of string to a sentence?如何将字符串数组转换为句子?
【发布时间】:2014-04-03 16:23:23
【问题描述】:

如何使用 Linq 查询方法将字符串数组转换为句子?

private static void Main()
{
    string sentence = "C# is fun.";
    string[] words = sentence.Split();
    //string temp= words;       
}

temp 想要与sentence 具有相同的值。

【问题讨论】:

  • LINQ 在这里做什么?
  • @rendon:只是为了学习 LINQ。
  • String.Join 是一个更好的选择。不要仅仅为了使用 LINQ 而使用 LINQ。

标签: c#


【解决方案1】:

你可以使用

var res = string.Join(" ", words);

string[] words = { "one", "two", "three" };
var res = words.Aggregate((current, next) => current + " " + next);

【讨论】:

  • 为什么,为什么,为什么words.ToArray?它已经是一个数组有什么意义?即使不是,string.Join 也将IEnumerable<T> 作为参数,因此您无需将其转换为列表或数组。
【解决方案2】:

你可以试试:

var temp = words.Aggregate((x, y) => x + " " + y);

【讨论】:

    【解决方案3】:
    string temp = words.Aggregate((workingSentence, next) => 
          workingSentence + " " + next);
    

    参考:http://msdn.microsoft.com/en-us/library/bb548651%28v=vs.110%29.aspx

    【讨论】:

      【解决方案4】:

      使用String.Join 方法:

      private static void Main()
      {
          string sentence = "C# is fun.";
          string[] words = sentence.Split();
      
          // Join the words back together, with a " " in between each one.
          string temp = String.Join(" ", words);
      }
      

      【讨论】:

      • 这里唯一的答案提供了一个应该在实际代码中使用的示例。
      猜你喜欢
      • 2022-01-20
      • 2021-12-13
      • 2011-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-11
      相关资源
      最近更新 更多