使用迭代器 遍历文件信息的详解
程序员文章站
2022-05-31 18:10:45
1.迭代文件的行复制代码 代码如下: public static ienumerable...
1.迭代文件的行
public static ienumerable<string> readlines(string filename)
{
using (textreader reader = file.opentext(filename))
{
string line;
if ((line = reader.readline()) != null)
{
yield return line;
}
}
}
static void main()
{
foreach (string line in iterator.readlines(""))
{
console.writeline(line);
}
}
2.使用迭代器和谓词对文件中的行进行筛选
public static ienumerable<t> where<t>(ienumerable<t> source, predicate<t> predicate)
{
if (source == null || predicate == null)
{
throw new argumentnullexception();
}
return whereimplemeter(source, predicate);
}
private static ienumerable<t> whereimplemeter<t>(ienumerable<t> source, predicate<t> predicate)
{
foreach (t item in source)
{
if (predicate(item))
{
yield return item;
}
}
}
static void main()
{
ienumerable<string> lines = file.readalllines(@"your file name");
predicate<string> predicate = delegate(string line)
{
return line.startswith("using");
};
foreach (string str in where(lines, predicate))
{
console.writeline(str);
}
}
复制代码 代码如下:
public static ienumerable<string> readlines(string filename)
{
using (textreader reader = file.opentext(filename))
{
string line;
if ((line = reader.readline()) != null)
{
yield return line;
}
}
}
static void main()
{
foreach (string line in iterator.readlines(""))
{
console.writeline(line);
}
}
2.使用迭代器和谓词对文件中的行进行筛选
复制代码 代码如下:
public static ienumerable<t> where<t>(ienumerable<t> source, predicate<t> predicate)
{
if (source == null || predicate == null)
{
throw new argumentnullexception();
}
return whereimplemeter(source, predicate);
}
private static ienumerable<t> whereimplemeter<t>(ienumerable<t> source, predicate<t> predicate)
{
foreach (t item in source)
{
if (predicate(item))
{
yield return item;
}
}
}
static void main()
{
ienumerable<string> lines = file.readalllines(@"your file name");
predicate<string> predicate = delegate(string line)
{
return line.startswith("using");
};
foreach (string str in where(lines, predicate))
{
console.writeline(str);
}
}