我试图计算文本文件中包含特定单词“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
2条答案
按热度按时间mnemlml81#
RegEx
解决此类问题。一个内衬示例:o2gm4chl2#
我会这么做
如果需要区分大小写,可以使用
line.ToUpper().IndexOf("UNIQUEID")