[英]Difficulty in writing LINQ Query
I have written a query to fetch count of lines matching the criteria. 我写了一个查询来获取符合条件的行数。
The linq query that i have used is: 我使用的linq查询是:
int result = File.ReadLines(filePath).Count(line => line.StartsWith(word));
Here, i require the lines matching the criteria not the count. 在这里,我要求符合条件的行而不是计数。 Please help 请帮忙
File.ReadLines(filePath).Where(line => line.StartsWith(word));
Just change it to a Where
instead. 只需将其更改为Where
。
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.where.aspx http://msdn.microsoft.com/en-us/library/system.linq.enumerable.where.aspx
Filters a sequence of values based on a predicate. 根据谓词过滤值序列。
var lines = File.ReadLines(filePath).Where(line => line.StartsWith(word));
var total = lines.Count;
IEnumerable<string> linesMatching = File.ReadLines(filePath)
.Where(line => line.StartsWith(word));
On this way you have the lines and - if you create a collection from it - also the count: 这样一来,您就可以找到相应的行,并且-如果您从中创建一个集合,还可以算出计数:
List<string> lines = linesMatching.ToList();
int count = lines.Count;
Note that you cannot reuse the query once it is executed since you're using File.ReadLines
which uses a StreamReader
under the hood. 请注意,查询一旦执行便无法重用,因为您正在使用File.ReadLines
,它在File.ReadLines
使用StreamReader
。 Once it was used it is disposed. 使用后将其丢弃。 So this will raise an exception since the query was already executed at ToList
: 因此,这将引发异常,因为查询已在ToList
执行:
int count = linesMatching.Count();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.