c# – 如何将一个ReadLine循环重构为Linq
发布时间:2020-12-15 23:45:32 所属栏目:百科 来源:网络整理
导读:我想使下面的代码更清洁(在旁观者的眼中). var lines = new StringReader(lotsOfIncomingLinesWithNewLineCharacters);var resultingLines = new Liststring();string line;while( (line = lines.ReadLine() ) != null ){ if( line.Substring(0,5) == "value
我想使下面的代码更清洁(在旁观者的眼中).
var lines = new StringReader(lotsOfIncomingLinesWithNewLineCharacters); var resultingLines = new List<string>(); string line; while( (line = lines.ReadLine() ) != null ) { if( line.Substring(0,5) == "value" ) { resultingLines.Add(line); } } 喜欢的东西 var resultingLinesQuery = lotsOfIncomingLinesWithNewLineCharacters .Where(s=>s.Substring(0,5) == "value ); 希望我已经说明我不希望将结果作为列表(不填充内存)并且StringReader不是必需的. 有一个天真的解决方案来创建扩展并在那里移动ReadLine但我感觉可能有更好的方法. 解决方法
基本上你需要一种从TextReader中提取线条的方法.这是一个只能迭代一次的简单解决方案:
public static IEnumerable<string> ReadLines(this TextReader reader) { string line; while ((line = reader.ReadLine()) != null) { yield return line; } } 您可以使用: var resultingLinesQuery = new StringReader(lotsOfIncomingLinesWithNewLineCharacters) .ReadLines() .Where(s => s.Substring(0,5) == "value"); 但理想情况下,您应该能够迭代IEnumerable< T>不止一次.如果你只需要这个字符串,你可以使用: public static IEnumerable<string> SplitIntoLines(this string text) { using (var reader = new StringReader(text)) { string line; while ((line = reader.ReadLine()) != null) { yield return line; } } } 然后: var resultingLinesQuery = lotsOfIncomingLinesWithNewLineCharacters .SplitIntoLines() .Where(s => s.Substring(0,5) == "value"); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |