使用迭代器 遍歷文件信息的詳解
更新時(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垃圾回收機(jī)制對(duì)內(nèi)存泄露的處理
本篇文章是關(guān)于PHP垃圾回收機(jī)制對(duì)內(nèi)存泄露的處理進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06PHP字符過濾函數(shù)去除字符串最后一個(gè)逗號(hào)(rtrim)
PHP字符過濾函數(shù)去除字符串最后一個(gè)逗號(hào),用php自帶的函數(shù)比較容易解決2013-03-03PHP如何獲取Cookie并實(shí)現(xiàn)模擬登錄
這篇文章主要介紹了PHP如何獲取Cookie并實(shí)現(xiàn)模擬登錄,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07PHP回調(diào)函數(shù)與匿名函數(shù)實(shí)例詳解
這篇文章主要介紹了PHP回調(diào)函數(shù)與匿名函數(shù),結(jié)合實(shí)例形式分析了php回調(diào)函數(shù)與匿名函數(shù)的具體功能、用法及相關(guān)注意事項(xiàng),需要的朋友可以參考下2017-08-08php算開始時(shí)間到過期時(shí)間的相隔的天數(shù)
php算開始時(shí)間到過期時(shí)間的相隔的天數(shù),同理可以實(shí)現(xiàn)相隔年,小時(shí),分,秒等數(shù)2011-01-01