利用yield return與IEnumerable(T)來讓ORM類別可以被集合化與尋訪
一般來說,如果我在進行ORM(Object Relational Mapping)類別的輸出,丟到外部要另外進行處理時,我都會調用System.Collections.Generic.List
IEnumerable的使用方式
IEnumerable
static void Main(string[] args)
{
IEnumerable<string> oTemp = new string[] { "小明", "小華", "小英", "老王" };
foreach (string obj in oTemp)
{
Console.WriteLine(obj);
}
Console.WriteLine("--- END ---");
Console.Read();
}
當然,要塞自訂的物件實體也沒問題。
class emp
{
public string cName {get; set;}
}
static void Main(string[] args)
{
IEnumerable<emp> oTemp = new emp[] {
new emp { cName = "小明" },
new emp { cName = "小華" },
};
foreach (emp obj in oTemp)
{
Console.WriteLine(obj.cName);
}
Console.WriteLine("--- END ---");
Console.Read();
}
接下來換yield return出場
現在問題來了,假設你從資料庫讀到了一千筆資料放在DataTable中,我們應該不會想要慢慢new到字串陣列再使其自動轉換成IEnumerable
class Program
{
static void Main(string[] args)
{
foreach (ORMEmployee obj in GetList.Employee())
{
Console.WriteLine(obj.cName);
}
Console.WriteLine("--- END ---");
Console.Read();
}
}
class ORMEmployee
{
public string cName { get; set; }
}
class GetList
{
public static IEnumerable<ORMEmployee> Employee()
{
//這裡可能取材自資料庫之類的東西
string[] aryEmployee = new string[] { "小明", "小華", "小英", "老王" };
foreach (string cTemp in aryEmployee)
{
yield return new ORMEmployee() { cName = cTemp };
}
}
}
當然啦,沒有List
Console.WriteLine(
Newtonsoft.Json.JsonConvert.SerializeObject(GetList.Employee())
);