Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split and join in C# using linq

Tags:

c#

linq

I have the below string array.

 string[] sentence = new string[] { "The quick brown", "fox jumps over", "the lazy dog." };

I want to split it with " " and rejoin with #. This is for learning linq in c#. I know i can easily manage this with replace and other built in features. But i am trying in this way.

 var sentenceresult = sentence.Select(c => c.Split(' '))

but how to apply "#" for each item?

like image 779
Tom Cruise Avatar asked Dec 25 '22 11:12

Tom Cruise


1 Answers

You can do this with String.Join.

This should give you the expected output:-

string[] result = sentence.Select(x => String.Join("#", x.Split(' ')))
                          .ToArray();

Fiddle.

Update:

Enumerable.Select projects each item from your array sentence. So when you say Select(x => x will iterate through your array and will hold follwoing values in each iteration:-

"The quick brown"
"fox jumps over"
"the lazy dog."

Now, consider just the first sentence. String.Join method:

Concatenates all the elements of a string array, using the specified separator between each element.

So when we say x.Split(' ') it will actually split "The quick brown" (remember we are considering the first sentence here) and return a string array which is joined with #. Similarly for other sentence it will join the sentence.

like image 138
Rahul Singh Avatar answered Dec 27 '22 18:12

Rahul Singh