Add Iterator pattern
This commit is contained in:
36
src/IteratorPattern/FileExample/LineReader.cs
Normal file
36
src/IteratorPattern/FileExample/LineReader.cs
Normal file
@@ -0,0 +1,36 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace IteratorPattern.FileExample
|
||||
{
|
||||
public class LineReader : IEnumerable<string>
|
||||
{
|
||||
public string FilePath { get; private set; }
|
||||
public LineReader(string filePath)
|
||||
{
|
||||
FilePath = filePath;
|
||||
}
|
||||
|
||||
IEnumerator IEnumerable.GetEnumerator()
|
||||
{
|
||||
return GetEnumerator();
|
||||
}
|
||||
|
||||
public IEnumerator<string> GetEnumerator()
|
||||
{
|
||||
using (TextReader reader = File.OpenText(FilePath))
|
||||
{
|
||||
string line;
|
||||
while ((line = reader.ReadLine()) != null)
|
||||
{
|
||||
yield return line;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
30
src/IteratorPattern/FileExample/ReadBigFilesExample.cs
Normal file
30
src/IteratorPattern/FileExample/ReadBigFilesExample.cs
Normal file
@@ -0,0 +1,30 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace IteratorPattern.FileExample
|
||||
{
|
||||
public class ReadBigFilesExample
|
||||
{
|
||||
public void Run()
|
||||
{
|
||||
string[] files = Directory.GetFiles("bin/Debug/IteratorPattern/FileExample/SampleFiles");
|
||||
var filesWithContent = from file in files
|
||||
where HasAnyLines(file)
|
||||
select file;
|
||||
|
||||
foreach (var fileWithContent in filesWithContent)
|
||||
{
|
||||
Console.WriteLine("File with content: {0}", fileWithContent);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private bool HasAnyLines(string file)
|
||||
{
|
||||
return new LineReader(file).Any();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user