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
2008-12-17 00:19:02
+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
2008-12-17 00:22:52
Yes, I only added it for readability :)
CMS
2008-12-17 00:24:30
Thanks for the hint on SelectMany! Awesome tip!
Dave Markle
2008-12-17 00:26:04
@CMS no worries. Omitting the parameter will match more than just space though - you'll get tabs etc. Handy trick.
Matt Hamilton
2008-12-17 00:32:51
+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
2008-12-17 00:28:42
+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
2008-12-17 00:33:16
I was looking for an example using language-integrated query syntax, so you are the winner.
guillermooo
2008-12-17 15:07:47
+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
2008-12-17 00:39:23