Linq


1.Linq概述

列表和实体

准备数据:

  1. public class Championship
  2. {
  3. public int Year { get; set; }
  4. public string First { get; set; }
  5. public string Second { get; set; }
  6. public string Third { get; set; }
  7. }

Championship

  1. public static class Formula1
  2. {
  3. private static List<Racer> racers;
  4.  
  5. public static IList<Racer> GetChampions()
  6. {
  7. if (racers == null)
  8. {
  9. racers = new List<Racer>();
  10. racers.Add(new Racer("Nino", "Farina", "Italy", , , new int[] { }, new string[] { "Alfa Romeo" }));
  11. racers.Add(new Racer("Alberto", "Ascari", "Italy", , , new int[] { , }, new string[] { "Ferrari" }));
  12. racers.Add(new Racer("Juan Manuel", "Fangio", "Argentina", , , new int[] { , , , , }, new string[] { "Alfa Romeo", "Maserati", "Mercedes", "Ferrari" }));
  13. racers.Add(new Racer("Mike", "Hawthorn", "UK", , , new int[] { }, new string[] { "Ferrari" }));
  14. racers.Add(new Racer("Phil", "Hill", "USA", , , new int[] { }, new string[] { "Ferrari" }));
  15. racers.Add(new Racer("John", "Surtees", "UK", , , new int[] { }, new string[] { "Ferrari" }));
  16. racers.Add(new Racer("Jim", "Clark", "UK", , , new int[] { , }, new string[] { "Lotus" }));
  17. racers.Add(new Racer("Jack", "Brabham", "Australia", , , new int[] { , , }, new string[] { "Cooper", "Brabham" }));
  18. racers.Add(new Racer("Denny", "Hulme", "New Zealand", , , new int[] { }, new string[] { "Brabham" }));
  19. racers.Add(new Racer("Graham", "Hill", "UK", , , new int[] { , }, new string[] { "BRM", "Lotus" }));
  20. racers.Add(new Racer("Jochen", "Rindt", "Austria", , , new int[] { }, new string[] { "Lotus" }));
  21. racers.Add(new Racer("Jackie", "Stewart", "UK", , , new int[] { , , }, new string[] { "Matra", "Tyrrell" }));
  22. racers.Add(new Racer("Emerson", "Fittipaldi", "Brazil", , , new int[] { , }, new string[] { "Lotus", "McLaren" }));
  23. racers.Add(new Racer("James", "Hunt", "UK", , , new int[] { }, new string[] { "McLaren" }));
  24. racers.Add(new Racer("Mario", "Andretti", "USA", , , new int[] { }, new string[] { "Lotus" }));
  25. racers.Add(new Racer("Jody", "Scheckter", "South Africa", , , new int[] { }, new string[] { "Ferrari" }));
  26. racers.Add(new Racer("Alan", "Jones", "Australia", , , new int[] { }, new string[] { "Williams" }));
  27. racers.Add(new Racer("Keke", "Rosberg", "Finland", , , new int[] { }, new string[] { "Williams" }));
  28. racers.Add(new Racer("Niki", "Lauda", "Austria", , , new int[] { , , }, new string[] { "Ferrari", "McLaren" }));
  29. racers.Add(new Racer("Nelson", "Piquet", "Brazil", , , new int[] { , , }, new string[] { "Brabham", "Williams" }));
  30. racers.Add(new Racer("Ayrton", "Senna", "Brazil", , , new int[] { , , }, new string[] { "McLaren" }));
  31. racers.Add(new Racer("Nigel", "Mansell", "UK", , , new int[] { }, new string[] { "Williams" }));
  32. racers.Add(new Racer("Alain", "Prost", "France", , , new int[] { , , , }, new string[] { "McLaren", "Williams" }));
  33. racers.Add(new Racer("Damon", "Hill", "UK", , , new int[] { }, new string[] { "Williams" }));
  34. racers.Add(new Racer("Jacques", "Villeneuve", "Canada", , , new int[] { }, new string[] { "Williams" }));
  35. racers.Add(new Racer("Mika", "Hakkinen", "Finland", , , new int[] { , }, new string[] { "McLaren" }));
  36. racers.Add(new Racer("Michael", "Schumacher", "Germany", , , new int[] { , , , , , , }, new string[] { "Benetton", "Ferrari" }));
  37. racers.Add(new Racer("Fernando", "Alonso", "Spain", , , new int[] { , }, new string[] { "Renault" }));
  38. racers.Add(new Racer("Kimi", "Räikkönen", "Finland", , , new int[] { }, new string[] { "Ferrari" }));
  39. racers.Add(new Racer("Lewis", "Hamilton", "UK", , , new int[] { }, new string[] { "McLaren" }));
  40. racers.Add(new Racer("Jenson", "Button", "UK", , , new int[] { }, new string[] { "Brawn GP" }));
  41. racers.Add(new Racer("Sebastian", "Vettel", "Germany", , , new int[] { , }, new string[] { "Red Bull Racing" }));
  42. }
  43.  
  44. return racers;
  45. }
  46.  
  47. private static List<Team> teams;
  48. public static IList<Team> GetContructorChampions()
  49. {
  50. if (teams == null)
  51. {
  52. teams = new List<Team>()
  53. {
  54. new Team("Vanwall", ),
  55. new Team("Cooper", , ),
  56. new Team("Ferrari", , , , , , , , , , , , , , , , ),
  57. new Team("BRM", ),
  58. new Team("Lotus", , , , , , , ),
  59. new Team("Brabham", , ),
  60. new Team("Matra", ),
  61. new Team("Tyrrell", ),
  62. new Team("McLaren", , , , , , , , ),
  63. new Team("Williams", , , , , , , , , ),
  64. new Team("Benetton", ),
  65. new Team("Renault", , ),
  66. new Team("Brawn GP", ),
  67. new Team("Red Bull Racing", , )
  68. };
  69. }
  70. return teams;
  71. }
  72.  
  73. private static List<Championship> championships;
  74. public static IEnumerable<Championship> GetChampionships()
  75. {
  76. if (championships == null)
  77. {
  78. championships = new List<Championship>();
  79. championships.Add(new Championship
  80. {
  81. Year = ,
  82. First = "Nino Farina",
  83. Second = "Juan Manuel Fangio",
  84. Third = "Luigi Fagioli"
  85. });
  86. championships.Add(new Championship
  87. {
  88. Year = ,
  89. First = "Juan Manuel Fangio",
  90. Second = "Alberto Ascari",
  91. Third = "Froilan Gonzalez"
  92. });
  93. championships.Add(new Championship
  94. {
  95. Year = ,
  96. First = "Alberto Ascari",
  97. Second = "Nino Farina",
  98. Third = "Piero Taruffi"
  99. });
  100. championships.Add(new Championship
  101. {
  102. Year = ,
  103. First = "Alberto Ascari",
  104. Second = "Juan Manuel Fangio",
  105. Third = "Nino Farina"
  106. });
  107. championships.Add(new Championship
  108. {
  109. Year = ,
  110. First = "Juan Manuel Fangio",
  111. Second = "Froilan Gonzalez",
  112. Third = "Mike Hawthorn"
  113. });
  114. championships.Add(new Championship
  115. {
  116. Year = ,
  117. First = "Juan Manuel Fangio",
  118. Second = "Stirling Moss",
  119. Third = "Eugenio Castellotti"
  120. });
  121. championships.Add(new Championship
  122. {
  123. Year = ,
  124. First = "Juan Manuel Fangio",
  125. Second = "Stirling Moss",
  126. Third = "Peter Collins"
  127. });
  128. championships.Add(new Championship
  129. {
  130. Year = ,
  131. First = "Juan Manuel Fangio",
  132. Second = "Stirling Moss",
  133. Third = "Luigi Musso"
  134. });
  135. championships.Add(new Championship
  136. {
  137. Year = ,
  138. First = "Mike Hawthorn",
  139. Second = "Stirling Moss",
  140. Third = "Tony Brooks"
  141. });
  142. championships.Add(new Championship
  143. {
  144. Year = ,
  145. First = "Jack Brabham",
  146. Second = "Tony Brooks",
  147. Third = "Stirling Moss"
  148. });
  149. championships.Add(new Championship
  150. {
  151. Year = ,
  152. First = "Jack Brabham",
  153. Second = "Bruce McLaren",
  154. Third = "Stirling Moss"
  155. });
  156. championships.Add(new Championship
  157. {
  158. Year = ,
  159. First = "Phil Hill",
  160. Second = "Wolfgang von Trips",
  161. Third = "Stirling Moss"
  162. });
  163. championships.Add(new Championship
  164. {
  165. Year = ,
  166. First = "Graham Hill",
  167. Second = "Jim Clark",
  168. Third = "Bruce McLaren"
  169. });
  170. championships.Add(new Championship
  171. {
  172. Year = ,
  173. First = "Jim Clark",
  174. Second = "Graham Hill",
  175. Third = "Richie Ginther"
  176. });
  177. championships.Add(new Championship
  178. {
  179. Year = ,
  180. First = "John Surtees",
  181. Second = "Graham Hill",
  182. Third = "Jim Clark"
  183. });
  184. championships.Add(new Championship
  185. {
  186. Year = ,
  187. First = "Jim Clark",
  188. Second = "Graham Hill",
  189. Third = "Jackie Stewart"
  190. });
  191. championships.Add(new Championship
  192. {
  193. Year = ,
  194. First = "Jack Brabham",
  195. Second = "John Surtees",
  196. Third = "Jochen Rindt"
  197. });
  198. championships.Add(new Championship
  199. {
  200. Year = ,
  201. First = "Dennis Hulme",
  202. Second = "Jack Brabham",
  203. Third = "Jim Clark"
  204. });
  205. championships.Add(new Championship
  206. {
  207. Year = ,
  208. First = "Graham Hill",
  209. Second = "Jackie Stewart",
  210. Third = "Dennis Hulme"
  211. });
  212. championships.Add(new Championship
  213. {
  214. Year = ,
  215. First = "Jackie Stewart",
  216. Second = "Jackie Ickx",
  217. Third = "Bruce McLaren"
  218. });
  219. championships.Add(new Championship
  220. {
  221. Year = ,
  222. First = "Jochen Rindt",
  223. Second = "Jackie Ickx",
  224. Third = "Clay Regazzoni"
  225. });
  226. championships.Add(new Championship
  227. {
  228. Year = ,
  229. First = "Jackie Stewart",
  230. Second = "Ronnie Peterson",
  231. Third = "Francois Cevert"
  232. });
  233. championships.Add(new Championship
  234. {
  235. Year = ,
  236. First = "Emerson Fittipaldi",
  237. Second = "Jackie Stewart",
  238. Third = "Dennis Hulme"
  239. });
  240. championships.Add(new Championship
  241. {
  242. Year = ,
  243. First = "Jackie Stewart",
  244. Second = "Emerson Fittipaldi",
  245. Third = "Ronnie Peterson"
  246. });
  247. championships.Add(new Championship
  248. {
  249. Year = ,
  250. First = "Emerson Fittipaldi",
  251. Second = "Clay Regazzoni",
  252. Third = "Jody Scheckter"
  253. });
  254. championships.Add(new Championship
  255. {
  256. Year = ,
  257. First = "Niki Lauda",
  258. Second = "Emerson Fittipaldi",
  259. Third = "Carlos Reutemann"
  260. });
  261. championships.Add(new Championship
  262. {
  263. Year = ,
  264. First = "James Hunt",
  265. Second = "Niki Lauda",
  266. Third = "Jody Scheckter"
  267. });
  268. championships.Add(new Championship
  269. {
  270. Year = ,
  271. First = "Niki Lauda",
  272. Second = "Jody Scheckter",
  273. Third = "Mario Andretti"
  274. });
  275. championships.Add(new Championship
  276. {
  277. Year = ,
  278. First = "Mario Andretti",
  279. Second = "Ronnie Peterson",
  280. Third = "Carlos Reutemann"
  281. });
  282. championships.Add(new Championship
  283. {
  284. Year = ,
  285. First = "Jody Scheckter",
  286. Second = "Gilles Villeneuve",
  287. Third = "Alan Jones"
  288. });
  289. championships.Add(new Championship
  290. {
  291. Year = ,
  292. First = "Alan Jones",
  293. Second = "Nelson Piquet",
  294. Third = "Carlos Reutemann"
  295. });
  296. championships.Add(new Championship
  297. {
  298. Year = ,
  299. First = "Nelson Piquet",
  300. Second = "Carlos Reutemann",
  301. Third = "Alan Jones"
  302. });
  303. championships.Add(new Championship
  304. {
  305. Year = ,
  306. First = "Keke Rosberg",
  307. Second = "Didier Pironi",
  308. Third = "John Watson"
  309. });
  310. championships.Add(new Championship
  311. {
  312. Year = ,
  313. First = "Nelson Piquet",
  314. Second = "Alain Prost",
  315. Third = "Rene Arnoux"
  316. });
  317. championships.Add(new Championship
  318. {
  319. Year = ,
  320. First = "Niki Lauda",
  321. Second = "Alain Prost",
  322. Third = "Elio de Angelis"
  323. });
  324. championships.Add(new Championship
  325. {
  326. Year = ,
  327. First = "Alain Prost",
  328. Second = "Michele Alboreto",
  329. Third = "Keke Rosberg"
  330. });
  331. championships.Add(new Championship
  332. {
  333. Year = ,
  334. First = "Alain Prost",
  335. Second = "Nigel Mansell",
  336. Third = "Nelson Piquet"
  337. });
  338. championships.Add(new Championship
  339. {
  340. Year = ,
  341. First = "Nelson Piquet",
  342. Second = "Nigel Mansell",
  343. Third = "Ayrton Senna"
  344. });
  345. championships.Add(new Championship
  346. {
  347. Year = ,
  348. First = "Ayrton Senna",
  349. Second = "Alain Prost",
  350. Third = "Gerhard Berger"
  351. });
  352. championships.Add(new Championship
  353. {
  354. Year = ,
  355. First = "Alain Prost",
  356. Second = "Ayrton Senna",
  357. Third = "Riccardo Patrese"
  358. });
  359. championships.Add(new Championship
  360. {
  361. Year = ,
  362. First = "Ayrton Senna",
  363. Second = "Alain Prost",
  364. Third = "Nelson Piquet"
  365. });
  366. championships.Add(new Championship
  367. {
  368. Year = ,
  369. First = "Ayrton Senna",
  370. Second = "Nigel Mansell",
  371. Third = "Riccardo Patrese"
  372. });
  373. championships.Add(new Championship
  374. {
  375. Year = ,
  376. First = "Nigel Mansell",
  377. Second = "Riccardo Patrese",
  378. Third = "Michael Schumacher"
  379. });
  380. championships.Add(new Championship
  381. {
  382. Year = ,
  383. First = "Alain Prost",
  384. Second = "Ayrton Senna",
  385. Third = "Damon Hill"
  386. });
  387. championships.Add(new Championship
  388. {
  389. Year = ,
  390. First = "Michael Schumacher",
  391. Second = "Damon Hill",
  392. Third = "Gerhard Berger"
  393. });
  394. championships.Add(new Championship
  395. {
  396. Year = ,
  397. First = "Michael Schumacher",
  398. Second = "Damon Hill",
  399. Third = "David Coulthard"
  400. });
  401. championships.Add(new Championship
  402. {
  403. Year = ,
  404. First = "Damon Hill",
  405. Second = "Jacques Villeneuve",
  406. Third = "Michael Schumacher"
  407. });
  408. championships.Add(new Championship
  409. {
  410. Year = ,
  411. First = "Jacques Villeneuve",
  412. Second = "Heinz-Harald Frentzen",
  413. Third = "David Coulthard"
  414. });
  415. championships.Add(new Championship
  416. {
  417. Year = ,
  418. First = "Mika Hakkinen",
  419. Second = "Michael Schumacher",
  420. Third = "David Coulthard"
  421. });
  422. championships.Add(new Championship
  423. {
  424. Year = ,
  425. First = "Mika Hakkinen",
  426. Second = "Eddie Irvine",
  427. Third = "Heinz-Harald Frentzen"
  428. });
  429. championships.Add(new Championship
  430. {
  431. Year = ,
  432. First = "Michael Schumacher",
  433. Second = "Mika Hakkinen",
  434. Third = "David Coulthard"
  435. });
  436. championships.Add(new Championship
  437. {
  438. Year = ,
  439. First = "Michael Schumacher",
  440. Second = "David Coulthard",
  441. Third = "Rubens Barrichello"
  442. });
  443. championships.Add(new Championship
  444. {
  445. Year = ,
  446. First = "Michael Schumacher",
  447. Second = "Rubens Barrichello",
  448. Third = "Juan Pablo Montoya"
  449. });
  450. championships.Add(new Championship
  451. {
  452. Year = ,
  453. First = "Michael Schumacher",
  454. Second = "Kimi Räikkönen",
  455. Third = "Juan Pablo Montoya"
  456. });
  457. championships.Add(new Championship
  458. {
  459. Year = ,
  460. First = "Michael Schumacher",
  461. Second = "Rubens Barrichello",
  462. Third = "Jenson Button"
  463. });
  464. championships.Add(new Championship
  465. {
  466. Year = ,
  467. First = "Fernando Alonso",
  468. Second = "Kimi Räikkönen",
  469. Third = "Michael Schumacher"
  470. });
  471. championships.Add(new Championship
  472. {
  473. Year = ,
  474. First = "Fernando Alonso",
  475. Second = "Michael Schumacher",
  476. Third = "Felipe Massa"
  477. });
  478. championships.Add(new Championship
  479. {
  480. Year = ,
  481. First = "Kimi Räikkönen",
  482. Second = "Lewis Hamilton",
  483. Third = "Fernando Alonso"
  484. });
  485. championships.Add(new Championship
  486. {
  487. Year = ,
  488. First = "Lewis Hamilton",
  489. Second = "Felipe Massa",
  490. Third = "Kimi Raikkonen"
  491. });
  492. championships.Add(new Championship
  493. {
  494. Year = ,
  495. First = "Jenson Button",
  496. Second = "Sebastian Vettel",
  497. Third = "Rubens Barrichello"
  498. });
  499. championships.Add(new Championship
  500. {
  501. Year = ,
  502. First = "Sebastian Vettel",
  503. Second = "Fernando Alonso",
  504. Third = "Mark Webber"
  505. });
  506. championships.Add(new Championship
  507. {
  508. Year = ,
  509. First = "Sebastian Vettel",
  510. Second = "Jenson Button",
  511. Third = "Mark Webber"
  512. });
  513. }
  514. return championships;
  515. }
  516.  
  517. private static IList<Racer> moreRacers;
  518. private static IList<Racer> GetMoreRacers()
  519. {
  520. if (moreRacers == null)
  521. {
  522. moreRacers = new List<Racer>();
  523. moreRacers.Add(new Racer("Luigi", "Fagioli", "Italy", starts: , wins: ));
  524. moreRacers.Add(new Racer("Jose Froilan", "Gonzalez", "Argentina", starts: , wins: ));
  525. moreRacers.Add(new Racer("Piero", "Taruffi", "Italy", starts: , wins: ));
  526. moreRacers.Add(new Racer("Stirling", "Moss", "UK", starts: , wins: ));
  527. moreRacers.Add(new Racer("Eugenio", "Castellotti", "Italy", starts: , wins: ));
  528. moreRacers.Add(new Racer("Peter", "Collins", "UK", starts: , wins: ));
  529. moreRacers.Add(new Racer("Luigi", "Musso", "Italy", starts: , wins: ));
  530. moreRacers.Add(new Racer("Tony", "Brooks", "UK", starts: , wins: ));
  531. moreRacers.Add(new Racer("Bruce", "McLaren", "New Zealand", starts: , wins: ));
  532. moreRacers.Add(new Racer("Wolfgang von", "Trips", "Germany", starts: , wins: ));
  533. moreRacers.Add(new Racer("Richie", "Ginther", "USA", starts: , wins: ));
  534. moreRacers.Add(new Racer("Jackie", "Ickx", "Belgium", starts: , wins: ));
  535. moreRacers.Add(new Racer("Clay", "Regazzoni", "Switzerland", starts: , wins: ));
  536. moreRacers.Add(new Racer("Ronnie", "Peterson", "Sweden", starts: , wins: ));
  537. moreRacers.Add(new Racer("Francois", "Cevert", "France", starts: , wins: ));
  538. moreRacers.Add(new Racer("Carlos", "Reutemann", "Argentina", starts: , wins: ));
  539. moreRacers.Add(new Racer("Gilles", "Villeneuve", "Canada", starts: , wins: ));
  540. moreRacers.Add(new Racer("Didier", "Pironi", "France", starts: , wins: ));
  541. moreRacers.Add(new Racer("John", "Watson", "UK", starts: , wins: ));
  542. moreRacers.Add(new Racer("Rene", "Arnoux", "France", starts: , wins: ));
  543. moreRacers.Add(new Racer("Elio", "de Angelis", "Italy", starts: , wins: ));
  544. moreRacers.Add(new Racer("Michele", "Alboreto", "Italy", starts: , wins: ));
  545. moreRacers.Add(new Racer("Gerhard", "Berger", "Austria", starts: , wins: ));
  546. moreRacers.Add(new Racer("Riccardo", "Patrese", "Italy", starts: , wins: ));
  547. moreRacers.Add(new Racer("David", "Coulthard", "UK", starts: , wins: ));
  548. moreRacers.Add(new Racer("Heinz-Harald", "Frentzen", "Germany", starts: , wins: ));
  549. moreRacers.Add(new Racer("Eddie", "Irvine", "UK", starts: , wins: ));
  550. moreRacers.Add(new Racer("Rubens", "Barrichello", "Brazil", starts: , wins: ));
  551. moreRacers.Add(new Racer("Juan Pablo", "Montoya", "Columbia", starts: , wins: ));
  552. moreRacers.Add(new Racer("Felipe", "Massa", "Brazil", starts: , wins: ));
  553. moreRacers.Add(new Racer("Mark", "Webber", "Australia", starts: , wins: ));
  554. }
  555. return moreRacers;
  556. }
  557. }

Formula1

  1. [Serializable]
  2. public class Racer : IComparable<Racer>, IFormattable
  3. {
  4. public Racer(string firstName, string lastName, string country, int starts, int wins)
  5. : this(firstName, lastName, country, starts, wins, null, null)
  6. {
  7. }
  8. public Racer(string firstName, string lastName, string country, int starts, int wins, IEnumerable<int> years, IEnumerable<string> cars)
  9. {
  10. this.FirstName = firstName;
  11. this.LastName = lastName;
  12. this.Country = country;
  13. this.Starts = starts;
  14. this.Wins = wins;
  15. this.Years = new List<int>(years);
  16. this.Cars = new List<string>(cars);
  17. }
  18. public string FirstName { get; set; }
  19. public string LastName { get; set; }
  20. public string Country { get; set; }
  21. public int Wins { get; set; }
  22. public int Starts { get; set; }
  23. public IEnumerable<string> Cars { get; private set; }
  24. public IEnumerable<int> Years { get; private set; }
  25.  
  26. public override string ToString()
  27. {
  28. return String.Format("{0} {1}", FirstName, LastName);
  29. }
  30.  
  31. public int CompareTo(Racer other)
  32. {
  33. if (other == null) return -;
  34. return string.Compare(this.LastName, other.LastName);
  35. }
  36.  
  37. public string ToString(string format)
  38. {
  39. return ToString(format, null);
  40. }
  41.  
  42. public string ToString(string format,
  43. IFormatProvider formatProvider)
  44. {
  45. switch (format)
  46. {
  47. case null:
  48. case "N":
  49. return ToString();
  50. case "F":
  51. return FirstName;
  52. case "L":
  53. return LastName;
  54. case "C":
  55. return Country;
  56. case "S":
  57. return Starts.ToString();
  58. case "W":
  59. return Wins.ToString();
  60. case "A":
  61. return String.Format("{0} {1}, {2}; starts: {3}, wins: {4}",
  62. FirstName, LastName, Country, Starts, Wins);
  63. default:
  64. throw new FormatException(String.Format("Format {0} not supported", format));
  65. }
  66. }
  67. }

Racer

  1. [Serializable]
  2. public class Team
  3. {
  4. public Team(string name, params int[] years)
  5. {
  6. this.Name = name;
  7. this.Years = new List<int>(years);
  8. }
  9. public string Name { get; private set; }
  10. public IEnumerable<int> Years { get; private set; }
  11. }

Team

Linq查询

查询来自巴西所有冠军:

  1. var query = from r in Formula1.GetChampions()
  2. where r.Country == "Brazil"
  3. orderby r.Wins descending
  4. select r;
  5.  
  6. foreach (var r in query)
  7. {
  8. Console.WriteLine("{0:A}", r);
  9. }

查询结果:

  1. Ayrton Senna, Brazil; starts: , wins:
  2. Nelson Piquet, Brazil; starts: , wins:
  3. Emerson Fittipaldi, Brazil; starts: , wins:

from where orderby select是linq查询中预定义的关键字.

查询语句以from开头以select或group子句结尾

扩展方法
  1. public static class StringExtension
  2. {
  3. public static void Foo(this string s)
  4. {
  5. Console.WriteLine("Foo invoked for {0}",s);
  6. }
  7. }

在Linq中,Linq为IEnumerable<T>接口提供了各种扩展方法,方便查询。

扩展方法必须在静态类中进行声明,定义一个静态方法,其中第一个参数定义了它扩展的类型。

对于string类,因为它是密封类,因此不能被继承,所以可以通过扩展方法来进行扩展string类。

我们扩展了string类,然后可以使用它的扩展方法:

  1. "你好".Fo(); //Foo invoked for 你好

这种扩展方法并没有违法面向对象的原则,因为定义了它的方法,并不能访问它的私有成员.

定义Linq扩展方法的类是Enumerable,只要导入这个空间,就可以访问该类的作用域。也就是说凡是继承该类的成员都可以访问了。下面列举了Where()扩展方法的实现代码。
Where()扩展方法的this关键字类型是IEnumerable,然后Where方法就可以应用与实现Ienumerable接口的每个类型,Where()扩展方法的Func<T,bool>委托,引用类返回布尔值,参数类型为T的方法。主要是检查IEnumerable<T>源中的项是否包含在目标集合中。如果委托引用了该方法,yield return语句就将源中的项返回给目标.

  1. public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source,Func<TSource,bool> predicate)
  2. {
  3. foreach(TSource item in source)
  4.   if(predicate(item))
  5.     yield return item;
  6. }

最后当我们调用时,只要实现了IEnumerable接口的所有类都可以使用该扩展方法

  1. static void ExtensionMethods()
  2. {
  3. var champions = new List<Racer>(Formula1.GetChampions());
  4. IEnumerable<Racer> brazilChampions =
  5. champions.Where(r => r.Country == "Brazil").
  6. OrderByDescending(r => r.Wins).
  7. Select(r => r);
  8.  
  9. foreach (Racer r in brazilChampions)
  10. {
  11. Console.WriteLine("{0:A}", r);
  12. }
  13. }
推迟查询的执行

在运行期间定义查询表达式时,查询不会运行,查询会在迭代数据项时运行

2.标准查询

筛选

使用where子句可以合并多个表达式

  1. var racers = from r in Formula1.GetChampions()
  2. where r.Wins > && (r.Country == "Brazil" || r.Country == "Austria")
  3. select r;
  4.  
  5. foreach (var r in racers)
  6. {
  7. Console.WriteLine("{0:A}", r);
  8. }

不是所有的查询都用linq语句,高级查询可以使用扩展方法

  1. var racers = Formula1.GetChampions().Where(r => r.Wins > && (r.Country == "Brazil" || r.Country == "Austria")).Select(r => r);
用索引筛选

在Where方法重载中,可以传递第2个参数——索引,扩展方法Where方法中,含有参数是Func<TSource, int, bool> predicate的委托,第2个类型是索引

  1. var racers = Formula1.GetChampions().
  2. Where((r, index) => r.LastName.StartsWith("A") && index % != );
  3. foreach (var r in racers)
  4. {
  5. Console.WriteLine("{0:A}", r);
  6. }
类型筛选

OfType扩展方法基于类型的筛选,通过指定的类型返回

  1. object[] data = { "one", , , "four", "five", };
  2. var query = data.OfType<int>();
  3. foreach (var s in query)
  4. {
  5. Console.WriteLine(s);// 2 3 6
  6. }
  7.  
  8. var query2 = data.OfType<string>();
  9. foreach (var s in query2)
  10. {
  11. Console.WriteLine(s);// one four five
  12. }
复合from子句

如果需要对对象的成员进行筛选,则需要使用复合from子句,这种方式类似于循环里面套循环

  1. var ferrariDrivers = from r in Formula1.GetChampions()
  2. from c in r.Cars
  3. where c == "Ferrari"
  4. orderby r.LastName
  5. select r.FirstName + " " + r.LastName;
  6.  
  7. foreach (var racer in ferrariDrivers)
  8. {
  9. Console.WriteLine(racer);
  10. }

C#把复合的from子句和linq查询转换为SelectMany扩展方法,SelectMany()方法可用于迭代序列的序列。

  1. public static IEnumerable<TResult> SelectMany<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, IEnumerable<TResult>> selector);
  1. var ferrariDrivers2 = Formula1.GetChampions().SelectMany(r => r.Cars, (r, c) => new { Racer = r, Car = c }).Where(r => r.Car == "Ferrari").OrderBy(r => r.Racer.FirstName).Select(r => r.Racer.FirstName + "" + r.Racer.LastName);
排序

使用orderby子句对序列进行排序,OrderBy()和OrderByDescending方法返回IOderEnumerable<TSource>,linq排序时多个关键字,逗号隔开.

  1. var racers2 = from r in Formula1.GetChampions()
  2. where r.Country == "Brazil"
  3. orderby r.Wins descending
  4. select r;
  1. var racers = (from r in Formula1.GetChampions()
  2. orderby r.Country, r.LastName, r.FirstName
  3. select r).Take();
  4.  
  5. foreach (var racer in racers)
  6. {
  7. Console.WriteLine("{0}: {1}, {2}", racer.Country, racer.LastName, racer.FirstName);
  8. }
  1. var racers2 = Formula1.GetChampions().OrderBy(r => r.Country).ThenBy(r => r.LastName).ThenBy(r => r.FirstName).Take();

使用ThenBy和ThenByDescending同样可以实现排序.Take方法提取了排序的前10个元素。

分组

要根据一个关键字值对查询结果分组,可以使用group子句。

  1. var countries = from r in Formula1.GetChampions()
  2. group r by r.Country into g
  3. orderby g.Count() descending, g.Key
  4. where g.Count() >=
  5. select new
  6. {
  7. Country = g.Key,
  8. Count = g.Count()
  9. };
  10.  
  11. foreach (var item in countries)
  12. {
  13. Console.WriteLine("{0, -10} {1}", item.Country, item.Count);
  14. }

代码中的标识符g,用来访问分组的结果信息。

要用扩展方法执行相同的操作。把groupby 子句解析为GroupBy()方法.

  1. var countries2 = Formula1.GetChampions().
  2. GroupBy(r => r.Country).
  3. OrderByDescending(g => g.Count()).
  4. ThenBy(g => g.Key).
  5. Where(g => g.Count() >= ).
  6. Select(g => new { Country = g.Key, Count = g.Count() });
对嵌套的对象分组

如果分组的对象应包含嵌套的序列,就可以改变select子句的创建的匿名类型

  1. var countries = from r in Formula1.GetChampions()
  2. group r by r.Country into g
  3. orderby g.Count() descending, g.Key
  4. where g.Count() >=
  5. select new
  6. {
  7. Country = g.Key,
  8. Count = g.Count(),
  9. Racers = from r1 in g
  10. orderby r1.LastName
  11. select r1.FirstName + " " + r1.LastName
  12. };
  13. foreach (var item in countries)
  14. {
  15. Console.WriteLine("{0, -10} {1}", item.Country, item.Count);
  16. foreach (var name in item.Racers)
  17. {
  18. Console.Write("{0}; ", name);
  19. }
  20. Console.WriteLine();
  21. }
内连接

使用join子句可以根据特定的条件合并两个数据源,但之前要获得两个要连接的列表。

  1. var racers = from r in Formula1.GetChampions()
  2. from y in r.Years
  3. select new
  4. {
  5. Year = y,
  6. Name = r.FirstName + " " + r.LastName
  7. };
  8.  
  9. var teams = from t in Formula1.GetContructorChampions()
  10. from y in t.Years
  11. select new
  12. {
  13. Year = y,
  14. Name = t.Name
  15. };
  1. var racersAndTeams =
  2. (from r in racers
  3. join t in teams on r.Year equals t.Year
  4. orderby t.Year
  5. select new
  6. {
  7. Year = r.Year,
  8. Champion = r.Name,
  9. Constructor = t.Name
  10. }).Take();
  11.  
  12. Console.WriteLine("Year World Champion\t Constructor Title");
  13. foreach (var item in racersAndTeams)
  14. {
  15. Console.WriteLine("{0}: {1,-20} {2}",
  16. item.Year, item.Champion, item.Constructor);
  17. }
左外连接

左外连接返回左边序列中的全部元素,即使他们在右边的序列中没有匹配的元素,左外连接用join子句和DefaultIfEmpty方法定义

  1. var racers = from r in Formula1.GetChampions()
  2. from y in r.Years
  3. select new
  4. {
  5. Year = y,
  6. Name = r.FirstName + " " + r.LastName
  7. };
  8.  
  9. var teams = from t in Formula1.GetContructorChampions()
  10. from y in t.Years
  11. select new
  12. {
  13. Year = y,
  14. Name = t.Name
  15. };
  16.  
  17. var racersAndTeams =
  18. (from r in racers
  19. join t in teams on r.Year equals t.Year into rt
  20. from t in rt.DefaultIfEmpty()
  21. orderby r.Year
  22. select new
  23. {
  24. Year = r.Year,
  25. Champion = r.Name,
  26. Constructor = t == null ? "no constructor championship" : t.Name
  27. }).Take();
  28.  
  29. Console.WriteLine("Year Champion\t\t Constructor Title");
  30. foreach (var item in racersAndTeams)
  31. {
  32. Console.WriteLine("{0}: {1,-20} {2}",
  33. item.Year, item.Champion, item.Constructor);
  34. }
组连接

左外连接使用了组连接和into子句,它有一部分语法和组连接相同,只不过组连接不使用DefaultIfEmpty方法,使用组连接时,可以连接两个独立的序列,对于其中一个序列中的某个元素,另一个序列中存在对应的一个项列表。

  1. var racers = Formula1.GetChampionships()
  2. .SelectMany(cs => new List<RacerInfo>()
  3. {
  4. new RacerInfo {
  5. Year = cs.Year,
  6. Position = ,
  7. FirstName = cs.First.FirstName(),
  8. LastName = cs.First.LastName()
  9. },
  10. new RacerInfo {
  11. Year = cs.Year,
  12. Position = ,
  13. FirstName = cs.Second.FirstName(),
  14. LastName = cs.Second.LastName()
  15. },
  16. new RacerInfo {
  17. Year = cs.Year,
  18. Position = ,
  19. FirstName = cs.Third.FirstName(),
  20. LastName = cs.Third.LastName()
  21. }
  22. });
  23.  
  24. var q = (from r in Formula1.GetChampions()
  25. join r2 in racers on
  26. new
  27. {
  28. FirstName = r.FirstName,
  29. LastName = r.LastName
  30. }
  31. equals
  32. new
  33. {
  34. FirstName = r2.FirstName,
  35. LastName = r2.LastName
  36. }
  37. into yearResults
  38. select new
  39. {
  40. FirstName = r.FirstName,
  41. LastName = r.LastName,
  42. Wins = r.Wins,
  43. Starts = r.Starts,
  44. Results = yearResults
  45. });
  46.  
  47. foreach (var r in q)
  48. {
  49. Console.WriteLine("{0} {1}", r.FirstName, r.LastName);
  50. foreach (var results in r.Results)
  51. {
  52. Console.WriteLine("{0} {1}", results.Year, results.Position);
  53. }
  54. }
集合操作

扩展方法Distinct()、Union()、Intersect()和Except()都是集合操作。

  1. Func<string, IEnumerable<Racer>> racersByCar =
  2. car => from r in Formula1.GetChampions()
  3. from c in r.Cars
  4. where c == car
  5. orderby r.LastName
  6. select r;
  7.  
  8. Console.WriteLine("World champion with Ferrari and McLaren");
  9. foreach (var racer in racersByCar("Ferrari").Intersect(racersByCar("McLaren")))
  10. {
  11. Console.WriteLine(racer);
  12. }
合并

Zip方法是.NET4中的,允许把2个相关的序列合并为一个

  1. var racers = Formula1.GetChampionships().SelectMany(cs => new List<RacerInfo>()
  2. {
  3. new RacerInfo {
  4. Year = cs.Year,
  5. Position = ,
  6. FirstName = cs.First.FirstName(),
  7. LastName = cs.First.LastName()
  8. },
  9. new RacerInfo {
  10. Year = cs.Year,
  11. Position = ,
  12. FirstName = cs.Second.FirstName(),
  13. LastName = cs.Second.LastName()
  14. },
  15. new RacerInfo {
  16. Year = cs.Year,
  17. Position = ,
  18. FirstName = cs.Third.FirstName(),
  19. LastName = cs.Third.LastName()
  20. }
  21. });
  22.  
  23. var nonChampions = racers.Select(r =>
  24. new
  25. {
  26. FirstName = r.FirstName,
  27. LastName = r.LastName
  28. }).Except(Formula1.GetChampions().Select(r =>
  29. new
  30. {
  31. FirstName = r.FirstName,
  32. LastName = r.LastName
  33. }));
  34.  
  35. foreach (var r in nonChampions)
  36. {
  37. Console.WriteLine("{0} {1}", r.FirstName, r.LastName);
  38. }
分区

扩展方法Take()和Skip()等可用于分页

  1. var racerNames = from r in Formula1.GetChampions()
  2. where r.Country == "Italy"
  3. orderby r.Wins descending
  4. select new
  5. {
  6. Name = r.FirstName + " " + r.LastName
  7. };
  8.  
  9. var racerNamesAndStarts = from r in Formula1.GetChampions()
  10. where r.Country == "Italy"
  11. orderby r.Wins descending
  12. select new
  13. {
  14. LastName = r.LastName,
  15. Starts = r.Starts
  16. };
聚合操作符

聚合操作符返回一个值(Count()、Sum()、Min()、Max()、Average()和Aggregate())

  1. int pageSize = ;
  2.  
  3. int numberPages = (int)Math.Ceiling(Formula1.GetChampions().Count() /
  4. (double)pageSize);
  5.  
  6. for (int page = ; page < numberPages; page++)
  7. {
  8. Console.WriteLine("Page {0}", page);
  9.  
  10. var racers =
  11. (from r in Formula1.GetChampions()
  12. orderby r.LastName, r.FirstName
  13. select r.FirstName + " " + r.LastName).
  14. Skip(page * pageSize).Take(pageSize);
  15.  
  16. foreach (var name in racers)
  17. {
  18. Console.WriteLine(name);
  19. }
  20. Console.WriteLine();
  21. }
  1. var countries = (from c in
  2. from r in Formula1.GetChampions()
  3. group r by r.Country into c
  4. select new
  5. {
  6. Country = c.Key,
  7. Wins = (from r1 in c
  8. select r1.Wins).Sum()
  9. }
  10. orderby c.Wins descending, c.Country
  11. select c).Take();
  12.  
  13. foreach (var country in countries)
  14. {
  15. Console.WriteLine("{0} {1}", country.Country, country.Wins);
  16. }
转换操作符

linq查询可以推迟到访问数据项时再执行。在迭代中使用查询时,查询会执行。使用转换操作符会立即执行查询。

  1. var list = new System.Collections.ArrayList(Formula1.GetChampions() as System.Collections.ICollection);
  2.  
  3. var query = from r in list.Cast<Racer>()
  4. where r.Country == "USA"
  5. orderby r.Wins descending
  6. select r;
  7. foreach (var racer in query)
  8. {
  9. Console.WriteLine("{0:A}", racer);
  10. }
生成操作符

生成操作符Range()、Empty()和Repear()不是扩展方法。是返回序列的静态方法.

  1. var values=Enumerable.Range(,);
  2. foreach(var item in values)
  3. {
  4. Console.Write("{0}",item);
  5. }

输出1到20的20个数字。

3.并行Linq

Linq中的ParallelEnumerable类可以分解查询的工作。使其分布在多个线程上。ParallelEnumerable类的大多数扩展方法是ParallelQuery<TSource>类的扩展。

并行查询

对于ParallelEnumerable类,查询是分区的,以便多个线程可以同时处理该查询。集合可以分多个部分,其中每个部分由不同的线程处理,以筛选其余项,完成分区的工作后,就需要合并,获得所有部分的总和。

  1. static IEnumerable<int> SampleData()
  2. {
  3. const int arraySize = ;
  4. var r = new Random();
  5. return Enumerable.Range(, arraySize).Select(x => r.Next()).ToList();
  6. }
  7.  
  8. static void IntroParallel()
  9. {
  10. var data = SampleData();
  11.  
  12. var watch = new Stopwatch();
  13.  
  14. watch.Start();
  15. var q1 = (from x in data
  16. where Math.Log(x) <
  17. select x).Average();
  18. watch.Stop();
  19. Console.WriteLine("sync {0}, result: {1}", watch.ElapsedMilliseconds, q1);
  20.  
  21. watch.Reset();
  22. watch.Start();
  23. var q2 = (from x in Partitioner.Create(data).AsParallel()
  24. where Math.Log(x) <
  25. select x).Average();
  26. watch.Stop();
  27. Console.WriteLine("async {0}, result: {1}", watch.ElapsedMilliseconds, q2);
  28. }
分区器

可以调用WithExecutionMode()和WithDegreeOfParallelism()方法,来影响并行机制。对于WithExecutionMode()方法可以传递ParallelExecutionMode的一个Default值或者ForceParallelism值。默认情况下,并行Linq避免使用系统开销很高的并行机制。对于WithDegreeOfParallelism()方法可以传递一个整数值,以指定应并行运行的最大任务数。查询不应使用全部CPU

  1. var res = (from x in data.AsParallel().WithCancellation(cts.Token)
  2. where Math.Log(x) <
  3. select x).Average();
取消

.NET提供了一个标准方式。来取消长时间运行的任务。要取消长时间运行的查询。可以给查询添加WithCancellation()方法,并传递一个CancellationToken令牌作为参数。CancellationToken令牌从CancellationTokenSource类中创建,该查询在单独的线程中运行。在该线程中。捕获一个异常。如果取消查询就触发这个异常。在主线程中,调用CancellationTokenSource类的Cancel()方法可以取消任务

  1. var cts = new CancellationTokenSource();
  2.  
  3. Task.Factory.StartNew(() =>
  4. {
  5. try
  6. {
  7. var res = (from x in data.AsParallel().WithCancellation(cts.Token)
  8. where Math.Log(x) <
  9. select x).Average();
  10. Console.WriteLine("query finished, result: {0}", res);
  11. }
  12. catch (OperationCanceledException ex)
  13. {
  14. Console.WriteLine(ex.Message);
  15. }
  16. });
  17.  
  18. Console.WriteLine("query started");
  19. Console.Write("cancel? ");
  20. string input = Console.ReadLine();
  21. if (input.ToLower().Equals("y"))
  22. {
  23. cts.Cancel();
  24. Console.WriteLine("sent a cancel");
  25. }

cts.Cancel();

4.表达式树

我个人觉得理解某种程序扩展是很有意义的。

比如:

学会ASP.NET WebForm的服务器控件,就学会了ASP.NET用户控件,

学会ASP.NET MVC的@Html的扩展,就学会了HTMLHelper的自定义扩展,

现在学会了Linq表达式,就得学会Linq表达式树的扩展.

表达式树用于表示针对数据源的结构化查询,这些数据源实现 IQueryable<T>

以下部分代码来自世界中心的专栏

首先我们看看这块代码:

  1. ParameterExpression exp1 = Expression.Parameter(typeof(int), "a");
  2. ParameterExpression exp2 = Expression.Parameter(typeof(int), "b");
  3. //表达式主体的构建
  4. BinaryExpression exp = Expression.Add(exp1, exp2);
  5. //表达式树的构建(如下定义,表达式的类型为Lambda
  6. //lambda表达式的类型为Func<int, int, int>)
  7. var lambda = Expression.Lambda<Func<int, int, int>>(exp, exp1, exp2);

Expression介绍

Expression.Parameter用于构建表达式树的参数.

Expression.Parameter(typeof(int), "a")构建了表达式树的参数a,数据类型为int
委托表达式:(a,b)=>a+b 中的参数a已经构建好了。
既然参数a构建好了,那么b就同样构建出来了,现在就有了下面的代码

ParameterExpression exp1 = Expression.Parameter(typeof(int), "a");
ParameterExpression exp2 = Expression.Parameter(typeof(int), "b");
构建了委托表达式:(a,b)=>a+b 中的参数(a,b)

接下来构建表达式a+b,即构建BinaryExpression 对象

BinaryExpression 表示具有二进制运算符的表达式。

BinaryExpression exp = Expression.Add(exp1, exp2);构建了表达式a+b

Expression.Lambda()方法用于构建lamdba表达式,构建lamdba表达式的方法很多。我们就先了解

var lambda = Expression.Lambda<Func<int, int, int>>(exp, exp1, exp2);

这是当前Lamdba方法的定义:

  1. public static Expression<TDelegate> Lambda<TDelegate>(Expression body, params ParameterExpression[] parameters);

Expression是表达式树的主体,凡是继承该类的都可以使用,BinaryExpression 就是继承了该类。

params ParameterExpression[] parameters用于传递多个参数值。注意Lamdba方法的第一个参数是表达式主体,第2个是参数列表

这里再重复一下另外一个问题。

当一个方法的参数列表超过3个的时候,需要考虑使用params或者对象进行传递数据.通常一个方法参数列表超过3个,那么第4个参数类型应该为params object[] objs,第4个参数需要使用params

最后这块代码:

  1. ParameterExpression exp1 = Expression.Parameter(typeof(int), "a");
  2. ParameterExpression exp2 = Expression.Parameter(typeof(int), "b");
  3. //表达式主体的构建
  4. BinaryExpression exp = Expression.Add(exp1, exp2);
  5. //表达式树的构建(如下定义,表达式的类型为Lambda
  6. //lambda表达式的类型为Func<int, int, int>)
  7. var lambda = Expression.Lambda<Func<int, int, int>>(exp, exp1, exp2);

构建了(a,b)=>a+b表达式,表达式返回类型为:Func<int,int,int>,这个由调用Lambda方法的类型约束决定。

接下来,考考你吧:

  1. ParameterExpression exp3 = Expression.Parameter(typeof(Person), "p");
  2. var property = Expression.Property(exp3, "Name");
  3. var lambda2 = Expression.Lambda<Func<Person, string>>(property, exp3);

这块代码构建了什么表达式:

Expression.Property(exp3, "Name")顾名思义就是给参数p提供了一个属性Name;

那么构建后的表达式应该是:

  1. p=>p.Name

接下来看看Where扩展方法中的表达式构建:

  1. ParameterExpression exp3 = Expression.Parameter(typeof(Person), "p");
  2. var property = Expression.Property(exp3, "Name");
  3. var lambda2 = Expression.Lambda<Func<Person, string>>(property, exp3);
  4.  
  5. //p=>p.Name == "daisy"
  6. List<Person> persons = new List<Person>()
  7. { new Person(){ Name = "daisy", age = },
  8. new Person(){ Name = "daisy", age = },
  9. new Person(){Name="dom", age=},
  10. new Person(){Name="caren", age=}};
  11. var compareExp = simpleCompare<Person>("Name", "daisy");
  12. var daisys = persons.Where(compareExp).ToList();
  13. foreach (var item in daisys)
  14. {
  15. Console.WriteLine("Name: " + item.Name + " Age: " + item.age);
  16. }
  17. Console.ReadKey();
  1. public static Func<TSource, bool> simpleCompare<TSource>(string property, object value)
  2. {
  3. var type = typeof(TSource); //解析传入的对象类型,通过该类型指定表达式的参数类型为该对象类型
  4. var pe = Expression.Parameter(type, "p");//构建表达式参数
  5. var propertyReference = Expression.Property(pe, property);//构建表达式的对象属性,属性名为value
  6. var constantReference = Expression.Constant(value);//构建一个常数,该常数不是表达式中的参数
  7. var binaryExpression = Expression.Equal(propertyReference, constantReference);//构建匹配的表达式 p.Name==value
  8.  
  9. //compile 是表达式的一个接口,生成该lambda表达式树对的委托
  10. var res = Expression.Lambda<Func<TSource, bool>>(binaryExpression, pe).Compile();//构建查询表达式:第一个参数为匹配表达式binaryExpression,第2个参数为对象
  11. // p=>p.Name==Value表达式构建成功
  12. return res;
  13. }
  14. //最后在调用时:persons.Where(compareExp).ToList();表现为:persons.Where(p=>p.Name==value).ToList();的形式

5.Linq提供程序

LINQ 提供程序为特定的数据源实现了标准的查询操作符。

LINQ 提供程序也许会实现LINQ 定义的更多扩展方法,但至少要实现标准操作符。

LINQ to XML 不仅实现了专门用于XML 的方法,还实现了其他方法,例如System.Xml.Linq 命名空间的Extensions 类定义的方法Elements()、 
Descendants 和Ancestors。 
LINQ 提供程序的实现方案是根据命名空间第一个参数的类型来选择的。

实现扩展方法的类的命名空间必须是打开的,否则扩展类就不在作用域内。

在LINQ to Objects 中定义的Wherer()方法参数和在LINQ to SQL中定义的Wherer()方法参数是不同的。 
LINQ to Objects 中的Wherer()方法是用Enumerable 类定义的: 
public static IEnumerable <TSource> Where <TSource> (this IEnumerable <TSource> source, Func <TSource, bool> predicate); 
在 System.Linq 命名空间中,还有另一个类实现了操作符Where。这个实现代码由LINQ to SQL 使用, 
这些代码在类Queryable 中: 
public static IQueryable <TSource> Where <TSource> (this IQueryable <TSource> source, Expression < Func <TSource, bool> > predicate); 
这两个类都在System.Linq 命名空间的System.Core 程序集中实现。

那么,它是如何定义的?使用了什么方法?

无论是用Func<TSource, bool>参数传送,还是用Expression< Func<TSource,bool>>参数传送,

λ表达式都是相同的。只是编译器的操作是不同的,它根据source 参数来选择。

编译器根据其参数选择最匹配的方法。

在LINQ to SQL 中定义的DataContext 类的GetTable()方法返回IQueryable<TSource>,因此LINQ to SQL 使用类Queryable 的Wherer()方法。 
LINQ to SQL 提供程序使用表达式树,实现了接口IQueryable 和IQueryProvider。

C#高级编程9 第11章 Linq的更多相关文章

  1. 读《C#高级编程》第1章问题

    读<C#高级编程>第1章 .Net机构体系笔记 网红的话:爸爸说我将来会是一个牛逼的程序员,因为我有一个梦,虽然脑壳笨但是做事情很能坚持. 本章主要是了解.Net的结构,都是一些概念,并没 ...

  2. C#高级编程9 第18章 部署

    C#高级编程9 第18章 部署 使用 XCopy 进行部署 本主题演示如何通过将应用程序文件从一台计算机复制到另一台计算机来部署应用程序. 1.将项目中生成的程序集复制到目标计算机,生成的程序集位于项 ...

  3. C#高级编程9 第17章 使用VS2013-C#特性

    C#高级编程9 第17章 使用VS2013 编辑定位到 如果默认勾选了这项,请去掉勾选,因为勾选之后解决方案的目录会根据当前文件选中. 可以设置项目并行生成数 版本控制软件设置 所有文本编辑器行号显示 ...

  4. C#高级编程9 第16章 错误和异常

    C#高级编程9 第16章 错误和异常 了解这章可以学会如何处理系统异常以及错误信息. System.Exception类是.NET运行库抛出的异常,可以继承它定义自己的异常类. try块代码包含的代码 ...

  5. C#高级编程笔记之第二章:核心C#

    变量的初始化和作用域 C#的预定义数据类型 流控制 枚举 名称空间 预处理命令 C#编程的推荐规则和约定 变量的初始化和作用域 初始化 C#有两个方法可以一确保变量在使用前进行了初始化: 变量是字段, ...

  6. Windows核心编程:第11章 Windows线程池

    Github https://github.com/gongluck/Windows-Core-Program.git //第11章 Windows线程池.cpp: 定义应用程序的入口点. // #i ...

  7. C#高级编程9 第14章 内存管理和指针

    C#高级编程9 内存管理和指针 后台内存管理 1) 值数据类型 在处理器的虚拟内存中有一个区域,称为栈,栈存储变量的浅副本数据,通过进入变量的作用域划分区域,通过离开变量的作用域释放. 栈的指针指向栈 ...

  8. C#高级编程(第9版) 第11章 LINQ 笔记

    概述语言集成查询(Language Integrated Query, LINQ)在C#编程语言中集成了查询语法,可以用相同的语法访问不同的数据源.LINQ提供了不同数据源的抽象层,所以可以使用相同的 ...

  9. python高级编程(第12章:优化学习)1

    # -*- coding: utf-8 -*-# python:2.x__author__ = 'Administrator'#由于5,6,7,8,9,10,11主要是在包,测试之类的学习所以这边就不 ...

随机推荐

  1. shell用户管理->

    用户的添加与删除练习 -> 脚本1(if then) 思路:1.条件测试, 脚本使用案例, 创建用户[交互式创建] 1.怎么交互式 read -p 2.接收到对应字符串怎么创建用户 userad ...

  2. github 优秀的开源项目

    https://github.com/wlcaption/AndroidMarket---- 这是手机应用商店,包含应用的下载,用户中心等内容 https://github.com/wlcaption ...

  3. 写在用Mac进行Java开发之前

    在用Mac进行开发之前,建议浏览以下几个概念. 1. 几个基础概念 - 计算机 计算机(computer)俗称电脑,发明者是约翰·冯·诺依曼,计算机是现代一种用于高速计算的电子计算机器,可以进行数值计 ...

  4. delphi 获取一个字符占用几个字节,方法

  5. (三)HttpClient 抓取图片

    第一节: HttpClient 抓取图片 这里pom.xml需要用到io输入输出: <dependency> <groupId>commons-io</groupId&g ...

  6. Python学习笔记:import sys模块(argv、path、platform、exit)

    sys模块是Python标准库中自带的一个模块. sys模块包括了一组非常实用的服务,内含很多函数方法和变量,用来处理Python运行时配置以及资源,从而可以与当前程序之外的系统环境交互,如:Pyth ...

  7. python中mock的使用

    什么是mock? mock在翻译过来有模拟的意思.这里要介绍的mock是辅助单元测试的一个模块.它允许您用模拟对象替换您的系统的部分,并对它们已使用的方式进行断言. 在Python2.x 中 mock ...

  8. GUC-8 小练习

    import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.uti ...

  9. linux 101 hacks 3null 改文件大小写 xargs

    禁止标准输出和错误信息的输出 当我们调试 shell 脚本的时候,我们往往不希望看到标准输出和标准错误的信息.我们可以使用/dev/nulll 来禁止标准错误的信息. 将标准输出重定向到/dev/nu ...

  10. HDU - 4420 2013icpc长春A 函数离散化 + st表

    思路:我们定义F(x) 为以x点为起点,向后(a - b)个里面有多少个白球,虽然x的范围是LL范围内的,但是白球的 个数只有1e5, 那么我们可以把连续一段相同的离散化到一起, 对于一个确定的长度为 ...