What do you think of words in an array of strings with LINQ?

For an array like {"one two", "three four five"}, how did you calculate the total number of words contained in it using LINQ?

+3
source share
4 answers

Or, if you want to use C # language extensions:

var words = (from line in new[] { "one two", "three four five" } from word in line.Split(' ', StringSplitOptions.RemoveEmptyEntries) select word).Count(); 
+2
source

You can do this with SelectMany:

 var stringArray = new[] {"one two", "three four five"}; var numWords = stringArray.SelectMany(segment => segment.Split(' ')).Count(); 

SelectMany aligns the resulting sequences into one sequence, and then projects a space for each element of the string array.

+6
source

I think Sum is more readable:

 var list = new string[] { "1", "2", "3 4 5" }; var count = list.Sum(words => words.Split().Length); 
+5
source

Not an answer to the question (to use LINQ to get the combined number of words in an array), but to add related information you can use strings.split and stringings.join to do the same:

FROM#:

 string[] StringArray = { "one two", "three four five" }; int NumWords = Strings.Split(Strings.Join(StringArray)).Length; 

Vb.Net:

  Dim StringArray() As String = {"one two", "three four five"} Dim NumWords As Integer = Split(Join(StringArray)).Length 
+1
source

All Articles