Split and join C # with linq

I have the following array of strings.

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

I want to split it into "" and reunite C #. This is for linq training in C #. I know that I can easily handle replacement and other built-in functions. But I try this way.

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

but how to apply "#" to each element?

+4
source share
3 answers

You can do this with String.Join.

This should give the expected result: -

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

Fiddle

Update:

Enumerable.Selectdesigns each element from your array sentence. Therefore, when you say that Select(x =>x will go through your array and will hold the values ​​in each iteration: -

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

. String.Join:

, .

, x.Split(' '), "The quick brown" (, ) , #. .

+6

, var sentenceresult = sentence.Select(c => c.Split(' ')), , .. IEnumerable<string[]>, . , , .

, SelectMany:

var sentenceresult = sentence.SelectMany(c => c.Split(' '));

string, , :

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

string.Join(sentenceresult), :

The#quick#brown#fox#jumps#over#the#lazy#dog.
+2

You can try a one line solution:

string[] res = sentence.Select(str => String.Join("#", str.Split())).ToArray();

Or if you want a single line:

string res2 = String.Join("#", sentence.SelectMany(str => str.Split()));
+2
source

Source: https://habr.com/ru/post/1619392/


All Articles