Given an array like {"one two", "three four five"}, how'd you calculate the total number of words contained in it using LINQ?
From stackoverflow
-
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...
Matt Hamilton : +1, but you can also omit the parameter to split since it's whitespace by default. http://msdn.microsoft.com/en-us/library/b873y76a.aspxCMS : Yes, I only added it for readability :)Dave Markle : Thanks for the hint on SelectMany! Awesome tip!Matt Hamilton : @CMS no worries. Omitting the parameter will match more than just space though - you'll get tabs etc. Handy trick. -
I think Sum is more readable:
var list = new string[] { "1", "2", "3 4 5" }; var count = list.Sum(words => words.Split().Length);
-
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();
guillermooo : I was looking for an example using language-integrated query syntax, so you are the winner. -
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
guillermooo : Thanks, I was interested in the LINQ translation, though.
0 comments:
Post a Comment