-1

How can I use Linq query methods to convert an array of string to a sentence?

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

The temp wants to have the same value as sentence.

kiss my armpit
  • 3,413
  • 1
  • 27
  • 50

4 Answers4

6

You can use

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

or

string[] words = { "one", "two", "three" };
var res = words.Aggregate((current, next) => current + " " + next);
Andzej Maciusovic
  • 4,306
  • 1
  • 29
  • 40
  • 1
    why, why, why `words.ToArray` ? it is already an array what's the point? even if it isn't, string.Join takes `IEnumerable` as parameter,so you don't need to convert it to a list or array. – Selman Genç Mar 02 '14 at 20:30
4

You can try:

var temp = words.Aggregate((x, y) => x + " " + y);
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
3
string temp = words.Aggregate((workingSentence, next) => 
      workingSentence + " " + next);

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

shahkalpesh
  • 33,172
  • 3
  • 63
  • 88
3

Use the String.Join method:

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);
}
abelenky
  • 63,815
  • 23
  • 109
  • 159