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

C# 如何使用linq扩展方法计算字符串数组中每行的字数,c#,linq,extension-methods,C#,Linq,Extension Methods,我有一个字符串数组,如下面的示例: string[] words = { "C#", "I like C#", "My string is this", "Just words", "Delegates and Linq"}; 要对每个字符串中的单词进行计数,非常简单,可以使用words.Split(“”).Len

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

string[] words = { "C#", "I like C#", 
                   "My string is this", 
                   "Just words", "Delegates and Linq"}; 
要对每个字符串中的单词进行计数,非常简单,可以使用
words.Split(“”).Length
foreach
创建一个包含每个字符串中单词数的数组,或者将单个计数直接放入一个数组中,我们称之为计数数组,使用查询语法:

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
    }
}
使用System.Collections.Generic;
使用System.Linq;
公共静态类扩展
{
公共静态int字数(此字符串为me)
{
返回我。拆分(“”)。长度;
}
}
班级计划
{
静态void Main(字符串[]参数)
{
string[]words={“C#”,“我喜欢C#”,
“我的字符串是这个”,
“只是文字”,“代表和林克”};
列出listaUmCountChars=words.Select(s=>s.WordCount()).ToList();//1 3 4 2 3
int totalWordCount=words.Sum(s=>s.WordCount());//13
}
}

var listaUmCountChars=words.Select(s=>s.Split(“”).Length)
作为
string.Split
返回数组,您应该使用
array.Length
而不是
Enumerable.Count
,这将不必要地迭代每个数组。