给定像{"one two","three four five"}这样的数组,你如何使用LINQ计算其中包含的单词总数?
你可以用SelectMany做到这一点:
var stringArray = new[] {"one two", "three four five"}; var numWords = stringArray.SelectMany(segment => segment.Split(' ')).Count();
SelectMany将生成的序列展平为一个序列,然后为字符串数组的每个项目投射一个空格分割...
我认为Sum更具可读性:
var list = new string[] { "1", "2", "3 4 5" }; var count = list.Sum(words => words.Split().Length);