如何使用linq扩展方法计算字符串数组每一行中的单词数

How to count the number of words in each line of an array of strings using linq extension methods

我有一个字符串数组,如下例所示:

string[] words = { "C#", "I like C#", 
                   "My string is this", 
                   "Just words", "Delegates and Linq"}; 

要计算每个字符串中的单词数非常简单,可以使用 words.Split(' ').Lengthforeach 创建一个数组,其中包含每个字符串中的单词数,或者将将单个计数直接放入数组中,我们称其为计数数组,查询语法为:

var countWordsArray = from s in words select s.TrimEnd(' ').Split(' ').Length;

我想做的是使用扩展方法,例如:

var CountWordsArray = words.Select(s => s...);

时间很长,但白天很短,非常感谢您的帮助。我确定我遗漏了一些基本的东西,但我不能完全理解它。

int wordCount = 
    words.Sum((w) => w.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                      .Length);

扩展方法翻译:

var listaUmCountChars = words.Select(s => s.Split(' ').Length);

您也可以创建一个扩展方法来计算字数。

using System.Collections.Generic;
using System.Linq;

public static class StringExtensions
{
    public static int WordCount(this string me)
    {
        return me.Split(' ').Length;
    }
}

class Program
{
    static void Main(string[] args)
    {
        string[] words = { "C#", "I like C#",
                "My string is this",
                "Just words", "Delegates and Linq"};
        List<int> listaUmCountChars = words.Select(s => s.WordCount()).ToList(); // 1 3 4 2 3
        int totalWordCount = words.Sum(s => s.WordCount()); // 13
    }
}