• λ我爱Aspx >> C#.Net >> C# 3.0新特性初步研究 Part6:使用查询表达式 _C#教程
  • C# 3.0新特性初步研究 Part6:使用查询表达式 _C#教程

  • :aspxer  Դ:internet  :2007-4-28 20:57:55  ؼ:c#
  • 查询表达式(Query Expression)

    大家都应该对SQL语句不陌生吧,在C# 2.0之前,嵌入到代码中的SQL就是下面这个样子:

    1public void Test()

    2{

    3SqlConnection c = new SqlConnection(…);

    4 c.Open();

    5 SqlCommand cmd = new SqlCommand(

    6 @“SELECT c.Name, c.Phone // queries in quotes

    7 FROM Customers c

    8 WHERE c.City = @p0”

    9 );

    10 cmd.Parameters[“@po”] = “London”; // arguments loosely bound

    11 DataReader dr = c.Execute(cmd);

    12 while (dr.Read()) {

    13 string name = r.GetString(0);

    14 string phone = r.GetString(1); // results loosely typed

    15 DateTime date = r.GetDateTime(2); // compiler can’t help catch mistakes

    16 }

    17 r.Close();

    18}

    在C# 3.0中,我们可以将“SQL语句”方便的运用到其他地方,当然这里并不是真正的SQL语句~~

    我觉得我会在以后的开发过程中使用很多以下的类似代码:

    1class Program

    2 {

    3 static void Main(string[] args)

    4 {

    5 var contacts = new List<Contact>();

    6

    7 contacts.Add(new Contact("Michael", "520-331-2718",

    8 "33140 SW Liverpool Lane", "WA"));

    9 contacts.Add(new Contact("Jennifer", "503-998-1177",

    10 "1245 NW Baypony Dr", "OR"));

    11 contacts.Add(new Contact("Sean", "515-127-3340",

    12 "55217 SW Estate Dr", "WA"));

    13

    14 var WAContacts =

    15 from c in contacts

    16 where c.State == "WA"

    17 select new { c.Name, c.Phone };

    18

    19 Console.WriteLine("Contacts in the state of Washington: ");

    Ҷƪл˵?
  • һƪC# 3.0新特性初步研究 Part5:匿名类型_C#教程
    һƪC# 4.0语言将出现重大改变,带来一段Code Preview _C#教程