linq 计数特定单词出现的行数

jvidinwx  于 2023-09-28  发布在  其他
关注(0)|答案(2)|浏览(90)

我试图计算文本文件中包含特定单词“uniqueId”的行数。
我使用了下面的代码,但总是得到0,我可以计算出大约1000+次的情况。

var total = 0;
char[] delimiters = new[] { '\r', '\n' };

using (StreamReader sr = new StreamReader(fi.FullName))
{
    while (!sr.EndOfStream)
    {
        var counts = sr
            .ReadLine()
            .Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
            .GroupBy(s => s)
            .Select(g => new { Word = g.Key, Count = g.Count() });
        var wc = counts.SingleOrDefault(c => c.Word == "uniqueId");
        total += (wc == null) ? 0 : wc.Count;
    }
}

文本文件条目示例:

2023-07-31 07:26:35.211|Message sent (value: '{"uniqueId":1527258,"Node":"13","lclDtm":"2023-07-31T07:18:38.803","utcDtm":"2023-07-31T11:18:38.803","errorCode":"E45"}'). Delivery status: Persisted; Partition: 1; Offset: 161454; Created (UTC): 7/31/2023 11:26:34 AM

2023-07-31 07:26:35.648|Message sent (value: '{"uniqueId":1527291,"Node":"13","lclDtm":"2023-07-31T07:19:15.444","utcDtm":"2023-07-31T11:19:15.444","errorCode":"E45"}'). Delivery status: Persisted; Partition: 1; Offset: 161455; Created (UTC): 7/31/2023 11:26:35 AM
mnemlml8

mnemlml81#

RegEx解决此类问题。一个内衬示例:

int count = File.ReadLines(fi.FullName).Count(line => Regex.IsMatch(line, "uniqueId"));
o2gm4chl

o2gm4chl2#

我会这么做

void countUniqueId()
{
    string inFile = @"D:\junk\input.txt";
    int count = 0;
    foreach (String line in File.ReadAllLines(inFile))
    {
        if (line.IndexOf("uniqueId") > 0) {
            count++;
        }
    }
    
    Console.WriteLine(count);
}

如果需要区分大小写,可以使用line.ToUpper().IndexOf("UNIQUEID")

相关问题