Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# LINQ字数统计_C#_Linq - Fatal编程技术网

C# LINQ字数统计

C# LINQ字数统计,c#,linq,C#,Linq,我需要按LINQ数数单词。下面是我用来计算长字符串数组中的单词数的代码,但这不是很有效: public static int WordCount(string haystack, string needle) { if (needle == null) { return 0; } string[] source = haystack.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',', '*'

我需要按LINQ数数单词。下面是我用来计算长字符串数组中的单词数的代码,但这不是很有效:

public static int WordCount(string haystack, string needle)
{
    if (needle == null)
    {
        return 0;
    }

    string[] source = haystack.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',', '*', '-' }, StringSplitOptions.RemoveEmptyEntries);
    var matchQuery = from word in source
        where word.ToLowerInvariant() == needle.ToLowerInvariant()
        select word;
    int count=matchQuery.Count();
    return count;
}
假设我有这样一个字符串:

Geo Prism GEO 1995 GEO* - ABS #16213899 HGEO-
如果我试图在上面的句子中找到GEO,我的例程将不会返回正确的计数:我希望4
我的例程出了什么问题?

我认为您的代码几乎是正确的,但您没有得到4的原因是因为您需要进行“包含”检查,因为最后一个地理位置是hgeo的一部分(假设您打算得到4,而不是3)

此外,您可能会发现,它为您分割文本提供了更好的里程:

Regex.Split(haystack, @"\W+")

这会将文本分割成一堆单词,忽略任何语法(未经测试,但我认为应该有效)

您可以将其作为LINQ的一行:

void Main()
{
    string data = "Geo Prism GEO 1995 GEO* - ABS #16213899 HGEO-";
    var target = "GEO";
    var count = data.Select((c, i) => data.Substring(i)).Count(sub => sub.ToUpper().StartsWith(target));
    Console.WriteLine(count.ToString());
}

结果:

4

随机注释:我通常发现
“?;:,*-”。ToCharray()
比无休止的
字符列表更容易阅读和键入。“然后我的例程无法按我想要的方式进行计数。”---然后它会做什么?另外,我使用您使用的分隔符计算3个“GEO”。“HGEO”不算数。LINQ和蓝牙一样,让一切变得更好。+1代表LINQ中的一行,但我不太喜欢它的阅读方式。谢谢你的代码。我开始学习LINQ…所以我在LINQ方面很弱。我需要对你的LINQ代码进行一些解释。(c,i)中存储的内容以及sub中存储的内容。为什么在此处使用StartsWith()。这将查找任何以该单词开头的单词。当任何单词以“H”开头时,如HGEO-,StartWith()如何工作。请详细说明ur linq查询的工作原理。换行符可提高可读性@托马斯:
String
继承了
IEnumerable
,因此您可以对其使用LINQ,因此
选择字符串中字符的((c,i)
。允许传递索引,因此它迭代字符串中每个可能的连续子字符串。计算(大写)以单词to find.sorry开头的子字符串在测试后在我的场景中不起作用。下面是代码字符串data=“Geo Prism Geo 1995 Geo*-ABS#16213899 HGEO-”var target=“Geo”;var count=data.Select((c,i)=>data.Substring(i)).count(sub=>sub.ToUpper().StartsWith(target));Console.WriteLine(count.ToString());
4