如何用LINQ计算字符串数组中的单词?

时间:2021-01-29 15:45:40

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

给定像{“one two”,“three four five”}这样的数组,你如何使用LINQ计算其中包含的单词总数?

4 个解决方案

#1


2  

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

或者,如果您想使用C#语言扩展:

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

#2


6  

You can do it with SelectMany:

你可以用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...

SelectMany将生成的序列展平为一个序列,然后为字符串数组的每个项目投射一个空格分割...

#3


5  

I think Sum is more readable:

我认为Sum更具可读性:

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

#4


1  

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:

不是问题的答案(就是使用LINQ来获取数组中的组合字数),但是为了添加相关信息,你可以使用strings.split和strings.join来做同样的事情:

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

#1


2  

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

或者,如果您想使用C#语言扩展:

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

#2


6  

You can do it with SelectMany:

你可以用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...

SelectMany将生成的序列展平为一个序列,然后为字符串数组的每个项目投射一个空格分割...

#3


5  

I think Sum is more readable:

我认为Sum更具可读性:

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

#4


1  

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:

不是问题的答案(就是使用LINQ来获取数组中的组合字数),但是为了添加相关信息,你可以使用strings.split和strings.join来做同样的事情:

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