C# 3.0語言新特性(四) - 查詢表達式
在C# 3.0語言中,查詢表達式成為編程語言的一個重要組成部分,它可以完成諸如以前一些SQL語句而完成的功能,該表達式可以得到很好的編譯時語法檢查。
例子:
void QueryExpressionDefinition()
{
var objContacts = new List<Contact>();
objContacts.Add(new Contact("Michael", "520-331-2718",
"33140 SW Liverpool Lane", "WA"));
objContacts.Add(new Contact("Jennifer", "503-998-1177",
"1245 NW Baypony Dr", "OR"));
objContacts.Add(new Contact("Sean", "515-127-3340",
"55217 SW Estate Dr", "WA"));
var WAContacts = from c in objContacts
where c.sState == "WA"
select new { c.sName,c.sPhone };
Console.WriteLine("Contacts in the state of Washington: ");
foreach (var c in WAContacts)
{
Console.WriteLine("Name: {0}, Phone: {1}", c.sName , c.sPhone );
}
}
public class Contact
{
public string sName;
public string sPhone;
public string sAddress;
public string sState;
public Contact(string name, string phone,
string address, string state)
{
sName = name;
sPhone = phone;
sAddress = address;
sState = state;
}
}
執行結果是:
Contacts in the state of Washington:
Name: Michael, Phone: 520-331-2718
Name: Sean, Phone: 515-127-3340
請按任意鍵繼續. . .
其中,var WAContacts = from c in objContacts
where c.sState == "WA"
select new { c.sName,c.sPhone };
是查詢表達式,它的基本含義是:
var WAContancts = objContacts.
Where( c=> c.sState == “WA”)
.Select( c=> new Contact(c.sName,c.sPhone));
其中的參數是Lambda表達式,它的含義是前面介紹過的delegate聲明的匿名方法。
而現在的查詢表達式則用到了擴展方法
(待續)