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

3
  • 2
    What has to do LINQ here? Commented Mar 2, 2014 at 20:24
  • 1
    @rendon: Just for learning LINQ. Commented Mar 2, 2014 at 20:25
  • 4
    String.Join is a better option here. Don't use LINQ just to use LINQ. Commented Mar 2, 2014 at 20:31

4 Answers 4

7

You can use

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

or

string[] words = { "one", "two", "three" };
var res = words.Aggregate((current, next) => current + " " + next);
Sign up to request clarification or add additional context in comments.

1 Comment

why, why, why words.ToArray ? it is already an array what's the point? even if it isn't, string.Join takes IEnumerable<T> as parameter,so you don't need to convert it to a list or array.
4

You can try:

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

Comments

4

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);
}

1 Comment

The only answer here which provides an example that should be used in real code.
3
string temp = words.Aggregate((workingSentence, next) => 
      workingSentence + " " + next);

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.