Accepted answer

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

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


You can do it with SelectMany:

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

SelectMany flattens the resulting sequences into one sequence, and then it projects a whitespace split for each item of the string array...


I think Sum is more readable:

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


Not an answer to the question (that was to use LINQ to get the combined word count in the array), but to add related information, you can use strings.split and strings.join to do the same:


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


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

Related Articles