使用迭代器 遍歷文件信息的詳解
更新時(shí)間:2013年06月08日 18:04:19 作者:
本篇文章是對(duì)使用迭代器 遍歷文件的信息進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
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.使用迭代器和謂詞對(duì)文件中的行進(jìn)行篩選
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);
}
}
復(fù)制代碼 代碼如下:
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.使用迭代器和謂詞對(duì)文件中的行進(jìn)行篩選
復(fù)制代碼 代碼如下:
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);
}
}
相關(guān)文章
php 上一篇,下一篇文章實(shí)現(xiàn)代碼與原理說明
就是對(duì)id對(duì)進(jìn)行order by id desc 或 order by id asc進(jìn)行排序,然后再判斷比當(dāng)前id> or小于當(dāng)前文章id的相同欄目的文章。2010-05-05
PHP使用imap_open實(shí)現(xiàn)讀取QQ郵箱
這篇文章主要為大家詳細(xì)介紹了PHP如何使用imap_open實(shí)現(xiàn)讀取QQ郵箱功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-02-02
在PHP中養(yǎng)成7個(gè)面向?qū)ο蟮暮昧?xí)慣
如果您尚未打算用 OO 原則創(chuàng)建應(yīng)用程序,則使用 PHP 的面向?qū)ο螅∣O)的語言特性,這 7 個(gè)習(xí)慣將幫助您開始在過程編程與 OO 編程之間進(jìn)行轉(zhuǎn)換。2010-07-07
PHP將二維數(shù)組某一個(gè)字段相同的數(shù)組合并起來的方法
這篇文章主要介紹了PHP將二維數(shù)組某一個(gè)字段相同的數(shù)組合并起來的方法,涉及PHP多維數(shù)組操作的相關(guān)技巧,需要的朋友可以參考下2016-02-02

