给定像{“one two”,“three four five”}这样的数组,你如何使用LINQ计算其中包含的单词总数?
答案 0 :(得分:6)
您可以使用SelectMany执行此操作:
var stringArray = new[] {"one two", "three four five"};
var numWords = stringArray.SelectMany(segment => segment.Split(' ')).Count();
SelectMany将生成的序列展平为一个序列,然后为字符串数组的每个项目投射一个空格分割...
答案 1 :(得分:5)
我认为Sum更具可读性:
var list = new string[] { "1", "2", "3 4 5" };
var count = list.Sum(words => words.Split().Length);
答案 2 :(得分:2)
或者如果您想使用C#语言扩展名:
var words = (from line in new[] { "one two", "three four five" }
from word in line.Split(' ', StringSplitOptions.RemoveEmptyEntries)
select word).Count();
答案 3 :(得分:1)
不是问题的答案(就是使用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