tags:

views:

193

answers:

4

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

+5  A: 

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

CMS
+1, but you can also omit the parameter to split since it's whitespace by default. http://msdn.microsoft.com/en-us/library/b873y76a.aspx
Matt Hamilton
Yes, I only added it for readability :)
CMS
Thanks for the hint on SelectMany! Awesome tip!
Dave Markle
@CMS no worries. Omitting the parameter will match more than just space though - you'll get tabs etc. Handy trick.
Matt Hamilton
+3  A: 

I think Sum is more readable:

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

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();
Greg Beech
I was looking for an example using language-integrated query syntax, so you are the winner.
guillermooo
+1  A: 

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:

C#:

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
Stefan
Thanks, I was interested in the LINQ translation, though.
guillermooo