稍微重构一下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集合
【编辑推荐】