Linq City集合描述
稍微重構一下Linq City集合
因為我們將在好幾個示例中重用這個Linq City集合,我決定把它封裝到一個"TravelOrganizer"類中,如下所示:
- using System;
- using System.Collections.Generic;
- public class TravelOrganizer
- {
- public List<Location> PlacesVisited
- {
- get
- {
- List<Location> cities = new List<Location>{
- & nbsp; & nbsp;new Location { City="London", Distance=4789, Country="UK" },
- & nbsp; & nbsp;new Location { City="Amsterdam", Distance=4869, Country="Netherlands" },
- & nbsp; & nbsp;new Location { City="San Francisco", Distance=684, Country="USA" },
- & nbsp; & nbsp;new Location { City="Las Vegas", Distance=872, Country="USA" },
- & nbsp; & nbsp;new Location { City="Boston", Distance=2488, Country="USA" },
- & nbsp; & nbsp;new Location { City="Raleigh", Distance=2363, Country="USA" },
- & nbsp; & nbsp;new Location { City="Chicago", Distance=1733, Country="USA" },
- & nbsp; & nbsp;new Location { City="Charleston", Distance=2421, Country="USA" },
- & nbsp; & nbsp;new Location { City="Helsinki", Distance=4771, Country="Finland" },
- & nbsp;new Location { City="Nice", Distance=5428, Country="France" },
- & nbsp; & nbsp;new Location { City="Dublin", Distance=4527, Country="Ireland" }
- & nbsp; & nbsp;};
- return cities;
- }
- }
- }
這使我只需要編寫如下的代碼就能得到跟上面同樣的結果:
- using System;
- using System.Collections.Generic;
- using System.Web;
- using System.Web.UI;
- using System.Query;
- public partial class Step3 : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- TravelOrganizer travel = new TravelOrganizer();
- GridView1.DataSource = from location in travel.PlacesVisited
- & nbsp; where location.Distance > 1000
- & nbsp; orderby location.Country, location.City
- & nbsp; select location;
- GridView1.DataBind();
- }
- }
LINQ很酷之處就是它是強類型的。這意味著:
1) 你的所有的查詢都會進行編譯時檢查。不像現在的SQL語句,你只有到運行時才會發現你的錯誤所 在。這意味著你在開發時就可以檢查你的代碼的正確性,例如,如果我把上面的"distance"誤寫成 了"distanse",編譯器將為我捕獲到這個錯誤。
2) 當你寫LINQ查詢的時候你將在VS或免費的Visual Web Developer中獲得智能感知的提示。這不僅加 快了編碼的輸入速度,而且使我們在處理無論簡單還是復雜的集合和數據源對象模型時都變得非常容易。以上介紹Linq City集合
【編輯推薦】