PageRenderTime 64ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/EntityFramework/Beta1/LINQ101/C#/SampleQueries/DataSetLinqSamples.cs

#
C# | 2574 lines | 2010 code | 550 blank | 14 comment | 42 complexity | ad57c51159d7888f3b8e3afe5e382f71 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. //Copyright (C) Microsoft Corporation. All rights reserved.
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Data.Linq;
  6. using System.Data.Common;
  7. using System.Diagnostics;
  8. using System.Linq;
  9. using SampleSupport;
  10. using System.Xml.Linq;
  11. using System.Text;
  12. using System.IO;
  13. using System.Windows.Forms;
  14. // version erickt1
  15. namespace DataSetSampleQueries
  16. {
  17. public static class CustomSequenceOperators
  18. {
  19. public static IEnumerable<S> Combine<S>(this IEnumerable<DataRow> first, IEnumerable<DataRow> second, System.Linq.Func<DataRow, DataRow, S> func)
  20. {
  21. using (IEnumerator<DataRow> e1 = first.GetEnumerator(), e2 = second.GetEnumerator())
  22. {
  23. while (e1.MoveNext() && e2.MoveNext())
  24. {
  25. yield return func(e1.Current, e2.Current);
  26. }
  27. }
  28. }
  29. }
  30. [Title("101 LINQ over DataSet Samples")]
  31. [Prefix("DataSetLinq")]
  32. class DataSetLinqSamples : SampleHarness
  33. {
  34. private DataSet testDS;
  35. public DataSetLinqSamples() {
  36. testDS = TestHelper.CreateTestDataset();
  37. }
  38. #region "Restriction Operators"
  39. [Category("Restriction Operators")]
  40. [Title("Where - Simple 1")]
  41. [Description("This sample uses where to find all elements of an array less than 5.")]
  42. public void DataSetLinq1() {
  43. var numbers = testDS.Tables["Numbers"].AsEnumerable();
  44. var lowNums = from n in numbers
  45. where n.Field<int>("number") < 5
  46. select n;
  47. Console.WriteLine("Numbers < 5:");
  48. foreach (var x in lowNums) {
  49. Console.WriteLine(x[0]);
  50. }
  51. }
  52. [Category("Restriction Operators")]
  53. [Title("Where - Simple 2")]
  54. [Description("This sample uses where to find all products that are out of stock.")]
  55. public void DataSetLinq2() {
  56. var products = testDS.Tables["Products"].AsEnumerable();
  57. var soldOutProducts = from p in products
  58. where p.Field<int>("UnitsInStock") == 0
  59. select p;
  60. Console.WriteLine("Sold out products:");
  61. foreach (var product in soldOutProducts) {
  62. Console.WriteLine(product.Field<string>("ProductName") + " is sold out!");
  63. }
  64. }
  65. [Category("Restriction Operators")]
  66. [Title("Where - Simple 3")]
  67. [Description("This sample uses where to find all products that are in stock and " +
  68. "cost more than 3.00 per unit.")]
  69. public void DataSetLinq3() {
  70. var products = testDS.Tables["Products"].AsEnumerable();
  71. var expensiveInStockProducts = from p in products
  72. where p.Field<int>("UnitsInStock") > 0
  73. where p.Field<decimal>("UnitPrice") > 3.00M
  74. select p;
  75. Console.WriteLine("In-stock products that cost more than 3.00:");
  76. foreach (var product in expensiveInStockProducts) {
  77. Console.WriteLine(product.Field<string>("ProductName") + " is in stock and costs more than 3.00.");
  78. }
  79. }
  80. [Category("Restriction Operators")]
  81. [Title("Where - Drilldown")]
  82. [Description("This sample uses where to find all customers in Washington " +
  83. "and then uses the resulting sequence to drill down into their " +
  84. "orders.")]
  85. public void DataSetLinq4() {
  86. var customers = testDS.Tables["Customers"].AsEnumerable();
  87. var waCustomers =
  88. from c in customers
  89. where c.Field<string>("Region") == "WA"
  90. select c;
  91. Console.WriteLine("Customers from Washington and their orders:");
  92. foreach (var customer in waCustomers) {
  93. Console.WriteLine("Customer {0}: {1}", customer.Field<string>("CustomerID"), customer["CompanyName"]);
  94. foreach (var order in customer.GetChildRows("CustomersOrders")) {
  95. Console.WriteLine(" Order {0}: {1}", order["OrderID"], order["OrderDate"]);
  96. }
  97. }
  98. }
  99. [Category("Restriction Operators")]
  100. [Title("Where - Indexed")]
  101. [Description("This sample demonstrates an indexed Where clause that returns digits whose name is " +
  102. "shorter than their value.")]
  103. public void DataSetLinq5() {
  104. var digits = testDS.Tables["Digits"].AsEnumerable();
  105. var shortDigits = digits.Where((digit, index) => digit.Field<string>(0).Length < index);
  106. Console.WriteLine("Short digits:");
  107. foreach (var d in shortDigits) {
  108. Console.WriteLine("The word " + d["digit"] + " is shorter than its value.");
  109. }
  110. }
  111. [Category("Restriction Operators")]
  112. [Title("Single - Simple")]
  113. [Description("Turns a seqeunce into a single result")]
  114. public void DataSetLinq106() {
  115. //create an table with a single row
  116. var singleRowTable = new DataTable("SingleRowTable");
  117. singleRowTable.Columns.Add("id", typeof(int));
  118. singleRowTable.Rows.Add(new object[] {1});
  119. var singleRow = singleRowTable.AsEnumerable().Single();
  120. Console.WriteLine(singleRow != null);
  121. }
  122. [Category("Restriction Operators")]
  123. [Title("Single - with Predicate")]
  124. [Description("Returns a single element based on the specified predicate")]
  125. public void DataSetLinq107() {
  126. //create an table with a two rows
  127. var table = new DataTable("MyTable");
  128. table.Columns.Add("id", typeof(int));
  129. table.Rows.Add(new object[] {1});
  130. table.Rows.Add(new object[] {2});
  131. var singleRow = table.AsEnumerable().Single(r => r.Field<int>("id") == 1);
  132. Console.WriteLine(singleRow != null);
  133. }
  134. #endregion
  135. #region "Projection Operators"
  136. [Category("Projection Operators")]
  137. [Title("Select - Simple 1")]
  138. [Description("This sample uses select to produce a sequence of ints one higher than " +
  139. "those in an existing array of ints.")]
  140. public void DataSetLinq6() {
  141. var numbers = testDS.Tables["Numbers"].AsEnumerable();
  142. var numsPlusOne =
  143. from n in numbers
  144. select n.Field<int>(0) + 1;
  145. Console.WriteLine("Numbers + 1:");
  146. foreach (var i in numsPlusOne) {
  147. Console.WriteLine(i);
  148. }
  149. }
  150. [Category("Projection Operators")]
  151. [Title("Select - Simple 2")]
  152. [Description("This sample uses select to return a sequence of just the names of a list of products.")]
  153. public void DataSetLinq7() {
  154. var products = testDS.Tables["Products"].AsEnumerable();
  155. var productNames =
  156. from p in products
  157. select p.Field<string>("ProductName");
  158. Console.WriteLine("Product Names:");
  159. foreach (var productName in productNames) {
  160. Console.WriteLine(productName);
  161. }
  162. }
  163. [Category("Projection Operators")]
  164. [Title("Select - Transformation")]
  165. [Description("This sample uses select to produce a sequence of strings representing " +
  166. "the text version of a sequence of ints.")]
  167. public void DataSetLinq8() {
  168. var numbers = testDS.Tables["Numbers"].AsEnumerable();
  169. string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
  170. var textNums = numbers.Select(p => strings[p.Field<int>("number")]);
  171. Console.WriteLine("Number strings:");
  172. foreach (var s in textNums) {
  173. Console.WriteLine(s);
  174. }
  175. }
  176. [Category("Projection Operators")]
  177. [Title("Select - Anonymous Types 1")]
  178. [Description("This sample uses select to produce a sequence of the uppercase " +
  179. "and lowercase versions of each word in the original array.")]
  180. public void DataSetLinq9() {
  181. var words = testDS.Tables["Words"].AsEnumerable();
  182. var upperLowerWords = words.Select(p => new {Upper = (p.Field<string>(0)).ToUpper(),
  183. Lower = (p.Field<string>(0)).ToLower()});
  184. foreach (var ul in upperLowerWords) {
  185. Console.WriteLine("Uppercase: "+ ul.Upper + ", Lowercase: " + ul.Lower);
  186. }
  187. }
  188. [Category("Projection Operators")]
  189. [Title("Select - Anonymous Types 2")]
  190. [Description("This sample uses select to produce a sequence containing text " +
  191. "representations of digits and whether their length is even or odd.")]
  192. public void DataSetLinq10() {
  193. var numbers = testDS.Tables["Numbers"].AsEnumerable();
  194. var digits = testDS.Tables["Digits"];
  195. string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
  196. var digitOddEvens = numbers.
  197. Select(n => new {Digit = digits.Rows[n.Field<int>("number")]["digit"],
  198. Even = (n.Field<int>("number") % 2 == 0)});
  199. foreach (var d in digitOddEvens) {
  200. Console.WriteLine("The digit {0} is {1}.", d.Digit, d.Even ? "even" : "odd");
  201. }
  202. }
  203. [Category("Projection Operators")]
  204. [Title("Select - Anonymous Types 3")]
  205. [Description("This sample uses select to produce a sequence containing some properties " +
  206. "of Products, including UnitPrice which is renamed to Price " +
  207. "in the resulting type.")]
  208. public void DataSetLinq11() {
  209. var products = testDS.Tables["Products"].AsEnumerable();
  210. var productInfos = products.
  211. Select(n => new {ProductName = n.Field<string>("ProductName"),
  212. Category = n.Field<string>("Category"), Price = n.Field<decimal>("UnitPrice")});
  213. Console.WriteLine("Product Info:");
  214. foreach (var productInfo in productInfos) {
  215. Console.WriteLine("{0} is in the category {1} and costs {2} per unit.", productInfo.ProductName, productInfo.Category, productInfo.Price);
  216. }
  217. }
  218. [Category("Projection Operators")]
  219. [Title("Select - Indexed")]
  220. [Description("This sample uses an indexed Select clause to determine if the value of ints " +
  221. "in an array match their position in the array.")]
  222. public void DataSetLinq12() {
  223. var numbers = testDS.Tables["Numbers"].AsEnumerable();
  224. var numsInPlace = numbers.Select((num, index) => new {Num = num.Field<int>("number"),
  225. InPlace = (num.Field<int>("number") == index)});
  226. Console.WriteLine("Number: In-place?");
  227. foreach (var n in numsInPlace) {
  228. Console.WriteLine("{0}: {1}", n.Num, n.InPlace);
  229. }
  230. }
  231. [Category("Projection Operators")]
  232. [Title("Select - Filtered")]
  233. [Description("This sample combines select and where to make a simple query that returns " +
  234. "the text form of each digit less than 5.")]
  235. public void DataSetLinq13() {
  236. var numbers = testDS.Tables["Numbers"].AsEnumerable();
  237. var digits = testDS.Tables["Digits"];
  238. var lowNums =
  239. from n in numbers
  240. where n.Field<int>("number") < 5
  241. select digits.Rows[n.Field<int>("number")].Field<string>("digit");
  242. Console.WriteLine("Numbers < 5:");
  243. foreach (var num in lowNums) {
  244. Console.WriteLine(num);
  245. }
  246. }
  247. [Category("Projection Operators")]
  248. [Title("SelectMany - Compound from 1")]
  249. [Description("This sample uses a compound from clause to make a query that returns all pairs " +
  250. "of numbers from both arrays such that the number from numbersA is less than the number " +
  251. "from numbersB.")]
  252. public void DataSetLinq14() {
  253. var numbersA = testDS.Tables["NumbersA"].AsEnumerable();
  254. var numbersB = testDS.Tables["NumbersB"].AsEnumerable();
  255. var pairs =
  256. from a in numbersA
  257. from b in numbersB
  258. where a.Field<int>("number") < b.Field<int>("number")
  259. select new {a = a.Field<int>("number") , b = b.Field<int>("number")};
  260. Console.WriteLine("Pairs where a < b:");
  261. foreach (var pair in pairs) {
  262. Console.WriteLine("{0} is less than {1}", pair.a, pair.b);
  263. }
  264. }
  265. [Category("Projection Operators")]
  266. [Title("SelectMany - Compound from 2")]
  267. [Description("This sample uses a compound from clause to select all orders where the " +
  268. "order total is less than 500.00.")]
  269. public void DataSetLinq15() {
  270. var customers = testDS.Tables["Customers"].AsEnumerable();
  271. var orders = testDS.Tables["Orders"].AsEnumerable();
  272. var smallOrders =
  273. from c in customers
  274. from o in orders
  275. where c.Field<string>("CustomerID") == o.Field<string>("CustomerID")
  276. && o.Field<decimal>("Total") < 500.00M
  277. select new {CustomerID = c.Field<string>("CustomerID"), OrderID = o.Field<int>("OrderID"),
  278. Total = o.Field<decimal>("Total")};
  279. ObjectDumper.Write(smallOrders);
  280. }
  281. [Category("Projection Operators")]
  282. [Title("SelectMany - Compound from 3")]
  283. [Description("This sample uses a compound from clause to select all orders where the " +
  284. "order was made in 1998 or later.")]
  285. public void DataSetLinq16() {
  286. var customers = testDS.Tables["Customers"].AsEnumerable();
  287. var orders = testDS.Tables["Orders"].AsEnumerable();
  288. var myOrders =
  289. from c in customers
  290. from o in orders
  291. where c.Field<string>("CustomerID") == o.Field<string>("CustomerID") &&
  292. o.Field<DateTime>("OrderDate") >= new DateTime(1998, 1, 1)
  293. select new {CustomerID = c.Field<string>("CustomerID"), OrderID = o.Field<int>("OrderID"),
  294. OrderDate = o.Field<DateTime>("OrderDate")};
  295. ObjectDumper.Write(myOrders);
  296. }
  297. [Category("Projection Operators")]
  298. [Title("SelectMany - from Assignment")]
  299. [Description("This sample uses a compound from clause to select all orders where the " +
  300. "order total is greater than 2000.00 and uses from assignment to avoid " +
  301. "requesting the total twice.")]
  302. public void DataSetLinq17() {
  303. var customers = testDS.Tables["Customers"].AsEnumerable();
  304. var orders = testDS.Tables["Orders"].AsEnumerable();
  305. var myOrders =
  306. from c in customers
  307. from o in orders
  308. let total = o.Field<decimal>("Total")
  309. where c.Field<string>("CustomerID") == o.Field<string>("CustomerID")
  310. && total >= 2000.0M
  311. select new {CustomerID = c.Field<string>("CustomerID"), OrderID = o.Field<int>("OrderID"), total};
  312. ObjectDumper.Write(myOrders);
  313. }
  314. [Category("Projection Operators")]
  315. [Title("SelectMany - Multiple from")]
  316. [Description("This sample uses multiple from clauses so that filtering on customers can " +
  317. "be done before selecting their orders. This makes the query more efficient by " +
  318. "not selecting and then discarding orders for customers outside of Washington.")]
  319. public void DataSetLinq18() {
  320. var customers = testDS.Tables["Customers"].AsEnumerable();
  321. var orders = testDS.Tables["Orders"].AsEnumerable();
  322. DateTime cutoffDate = new DateTime(1997, 1, 1);
  323. var myOrders =
  324. from c in customers
  325. where c.Field<string>("Region") == "WA"
  326. from o in orders
  327. where c.Field<string>("CustomerID") == o.Field<string>("CustomerID")
  328. && (DateTime) o["OrderDate"] >= cutoffDate
  329. select new {CustomerID = c.Field<string>("CustomerID"), OrderID = o.Field<int>("OrderID")};
  330. ObjectDumper.Write(myOrders);
  331. }
  332. [Category("Projection Operators")]
  333. [Title("SelectMany - Indexed")]
  334. [Description("This sample uses an indexed SelectMany clause to select all orders, " +
  335. "while referring to customers by the order in which they are returned " +
  336. "from the query.")]
  337. public void DataSetLinq19() {
  338. var customers = testDS.Tables["Customers"].AsEnumerable();
  339. var orders = testDS.Tables["Orders"].AsEnumerable();
  340. var customerOrders =
  341. customers.SelectMany(
  342. (cust, custIndex) =>
  343. orders.Where(o => cust.Field<string>("CustomerID") == o.Field<string>("CustomerID"))
  344. .Select(o => new {CustomerIndex = custIndex + 1, OrderID = o.Field<int>("OrderID")}));
  345. foreach(var c in customerOrders) {
  346. Console.WriteLine("Customer Index: " + c.CustomerIndex +
  347. " has an order with OrderID " + c.OrderID);
  348. }
  349. }
  350. #endregion
  351. #region "Partioning Operators"
  352. [Category("Partitioning Operators")]
  353. [Title("Take - Simple")]
  354. [Description("This sample uses Take to get only the first 3 elements of " +
  355. "the array.")]
  356. public void DataSetLinq20() {
  357. var numbers = testDS.Tables["Numbers"].AsEnumerable();
  358. var first3Numbers = numbers.Take(3);
  359. Console.WriteLine("First 3 numbers:");
  360. foreach (var n in first3Numbers) {
  361. Console.WriteLine(n.Field<int>("number"));
  362. }
  363. }
  364. [Category("Partitioning Operators")]
  365. [Title("Take - Nested")]
  366. [Description("This sample uses Take to get the first 3 orders from customers " +
  367. "in Washington.")]
  368. public void DataSetLinq21() {
  369. var customers = testDS.Tables["Customers"].AsEnumerable();
  370. var orders = testDS.Tables["Orders"].AsEnumerable();
  371. var first3WAOrders = (
  372. from c in customers
  373. from o in orders
  374. where c.Field<string>("CustomerID") == o.Field<string>("CustomerID")
  375. && c.Field<string>("Region") == "WA"
  376. select new {CustomerID = c.Field<string>("CustomerID"), OrderID = o.Field<int>("OrderID"),
  377. OrderDate = o.Field<DateTime>("OrderDate")} ).Take(3);
  378. Console.WriteLine("First 3 orders in WA:");
  379. foreach (var order in first3WAOrders) {
  380. ObjectDumper.Write(order);
  381. }
  382. }
  383. [Category("Partitioning Operators")]
  384. [Title("Skip - Simple")]
  385. [Description("This sample uses Skip to get all but the first 4 elements of " +
  386. "the array.")]
  387. public void DataSetLinq22() {
  388. var numbers = testDS.Tables["Numbers"].AsEnumerable();
  389. var allButFirst4Numbers = numbers.Skip(4);
  390. Console.WriteLine("All but first 4 numbers:");
  391. foreach (var n in allButFirst4Numbers) {
  392. Console.WriteLine(n.Field<int>("number"));
  393. }
  394. }
  395. [Category("Partitioning Operators")]
  396. [Title("Skip - Nested")]
  397. [Description("This sample uses Skip to get all but the first 2 orders from customers " +
  398. "in Washington.")]
  399. public void DataSetLinq23() {
  400. var customers = testDS.Tables["Customers"].AsEnumerable();
  401. var orders = testDS.Tables["Orders"].AsEnumerable();
  402. var allButFirst2Orders = (
  403. from c in customers
  404. from o in orders
  405. where c.Field<string>("CustomerID") == o.Field<string>("CustomerID")
  406. && c.Field<string>("Region") == "WA"
  407. select new {CustomerID = c.Field<string>("CustomerID"), OrderID = o.Field<int>("OrderID"),
  408. OrderDate = o.Field<DateTime>("OrderDate")} ).Skip(2);
  409. Console.WriteLine("All but first 2 orders in WA:");
  410. foreach (var order in allButFirst2Orders) {
  411. ObjectDumper.Write(order);
  412. }
  413. }
  414. [Category("Partitioning Operators")]
  415. [Title("TakeWhile - Simple")]
  416. [Description("This sample uses TakeWhile to return elements starting from the " +
  417. "beginning of the array until a number is hit that is not less than 6.")]
  418. public void DataSetLinq24() {
  419. var numbers = testDS.Tables["Numbers"].AsEnumerable();
  420. var firstNumbersLessThan6 = numbers.TakeWhile(n => n.Field<int>("number") < 6);
  421. Console.WriteLine("First numbers less than 6:");
  422. foreach (var n in firstNumbersLessThan6) {
  423. Console.WriteLine(n.Field<int>("number"));
  424. }
  425. }
  426. [Category("Partitioning Operators")]
  427. [Title("TakeWhile - Indexed")]
  428. [Description("This sample uses TakeWhile to return elements starting from the " +
  429. "beginning of the array until a number is hit that is less than its position " +
  430. "in the array.")]
  431. public void DataSetLinq25() {
  432. var numbers = testDS.Tables["Numbers"].AsEnumerable();
  433. var firstSmallNumbers = numbers.TakeWhile((n, index) => n.Field<int>("number") >= index);
  434. Console.WriteLine("First numbers not less than their position:");
  435. foreach (var n in firstSmallNumbers) {
  436. Console.WriteLine(n.Field<int>("number"));
  437. }
  438. }
  439. [Category("Partitioning Operators")]
  440. [Title("SkipWhile - Simple")]
  441. [Description("This sample uses SkipWhile to get the elements of the array " +
  442. "starting from the first element divisible by 3.")]
  443. public void DataSetLinq26() {
  444. var numbers = testDS.Tables["Numbers"].AsEnumerable();
  445. var allButFirst3Numbers = numbers.SkipWhile(n => n.Field<int>("number") % 3 != 0);
  446. Console.WriteLine("All elements starting from first element divisible by 3:");
  447. foreach (var n in allButFirst3Numbers) {
  448. Console.WriteLine(n.Field<int>("number"));
  449. }
  450. }
  451. [Category("Partitioning Operators")]
  452. [Title("SkipWhile - Indexed")]
  453. [Description("This sample uses SkipWhile to get the elements of the array " +
  454. "starting from the first element less than its position.")]
  455. public void DataSetLinq27() {
  456. var numbers = testDS.Tables["Numbers"].AsEnumerable();
  457. var laterNumbers = numbers.SkipWhile((n, index) => n.Field<int>("number") >= index);
  458. Console.WriteLine("All elements starting from first element less than its position:");
  459. foreach (var n in laterNumbers) {
  460. Console.WriteLine(n.Field<int>("number"));
  461. }
  462. }
  463. #endregion
  464. #region "Ordering Operators"
  465. [Category("Ordering Operators")]
  466. [Title("OrderBy - Simple 1")]
  467. [Description("This sample uses orderby to sort a list of words alphabetically.")]
  468. public void DataSetLinq28() {
  469. var words = testDS.Tables["Words"].AsEnumerable();
  470. var sortedWords =
  471. from w in words
  472. orderby w.Field<string>("word")
  473. select w;
  474. Console.WriteLine("The sorted list of words:");
  475. foreach (var w in sortedWords) {
  476. Console.WriteLine(w.Field<string>("word"));
  477. }
  478. }
  479. [Category("Ordering Operators")]
  480. [Title("OrderBy - Simple 2")]
  481. [Description("This sample uses orderby to sort a list of words by length.")]
  482. public void DataSetLinq29() {
  483. var words = testDS.Tables["Words"].AsEnumerable();
  484. var sortedWords =
  485. from w in words
  486. orderby w.Field<string>("word").Length
  487. select w;
  488. Console.WriteLine("The sorted list of words (by length):");
  489. foreach (var w in sortedWords) {
  490. Console.WriteLine(w.Field<string>("word"));
  491. }
  492. }
  493. [Category("Ordering Operators")]
  494. [Title("OrderBy - Simple 3")]
  495. [Description("This sample uses orderby to sort a list of products by name.")]
  496. public void DataSetLinq30() {
  497. var products = testDS.Tables["Products"].AsEnumerable();
  498. var sortedProducts =
  499. from p in products
  500. orderby p.Field<string>("ProductName")
  501. select p.Field<string>("ProductName");
  502. ObjectDumper.Write(sortedProducts);
  503. }
  504. private class CaseInsensitiveComparer : IComparer<string>
  505. {
  506. public int Compare(string x, string y)
  507. {
  508. return string.Compare(x, y, true);
  509. }
  510. }
  511. [Category("Ordering Operators")]
  512. [Title("OrderBy - Comparer")]
  513. [Description("This sample uses an OrderBy clause with a custom comparer to " +
  514. "do a case-insensitive sort of the words in an array.")]
  515. [LinkedClass("CaseInsensitiveComparer")]
  516. public void DataSetLinq31() {
  517. var words3 = testDS.Tables["Words3"].AsEnumerable();
  518. var sortedWords = words3.OrderBy(a => a.Field<string>("word"), new CaseInsensitiveComparer());
  519. foreach (var dr in sortedWords)
  520. {
  521. Console.WriteLine(dr.Field<string>("word"));
  522. }
  523. }
  524. [Category("Ordering Operators")]
  525. [Title("OrderByDescending - Simple 1")]
  526. [Description("This sample uses orderby and descending to sort a list of " +
  527. "doubles from highest to lowest.")]
  528. public void DataSetLinq32() {
  529. var doubles = testDS.Tables["Doubles"].AsEnumerable();
  530. var sortedDoubles =
  531. from d in doubles
  532. orderby d.Field<double>("double") descending
  533. select d.Field<double>("double");
  534. Console.WriteLine("The doubles from highest to lowest:");
  535. foreach (var d in sortedDoubles) {
  536. Console.WriteLine(d);
  537. }
  538. }
  539. [Category("Ordering Operators")]
  540. [Title("OrderByDescending - Simple 2")]
  541. [Description("This sample uses orderby to sort a list of products by units in stock " +
  542. "from highest to lowest.")]
  543. public void DataSetLinq33() {
  544. var products = testDS.Tables["Products"].AsEnumerable();
  545. var sortedProducts =
  546. from p in products
  547. orderby p.Field<int>("UnitsInStock") descending
  548. select p.Field<int>("UnitsInStock") ;
  549. ObjectDumper.Write(sortedProducts);
  550. }
  551. [Category("Ordering Operators")]
  552. [Title("OrderByDescending - Comparer")]
  553. [Description("This sample uses an OrderBy clause with a custom comparer to " +
  554. "do a case-insensitive descending sort of the words in an array.")]
  555. [LinkedClass("CaseInsensitiveComparer")]
  556. public void DataSetLinq34() {
  557. var words3 = testDS.Tables["Words3"].AsEnumerable();
  558. var sortedWords = words3.OrderByDescending(a => a.Field<string>("word"), new CaseInsensitiveComparer());
  559. foreach (var dr in sortedWords)
  560. {
  561. Console.WriteLine(dr.Field<string>("word"));
  562. }
  563. }
  564. [Category("Ordering Operators")]
  565. [Title("ThenBy - Simple")]
  566. [Description("This sample uses a compound orderby to sort a list of digits, " +
  567. "first by length of their name, and then alphabetically by the name itself.")]
  568. public void DataSetLinq35() {
  569. var digits = testDS.Tables["Digits"].AsEnumerable();
  570. var sortedDigits =
  571. from d in digits
  572. orderby d.Field<string>("digit").Length, d.Field<string>("digit")[0]
  573. select d.Field<string>("digit");
  574. Console.WriteLine("Sorted digits by Length then first character:");
  575. foreach (var d in sortedDigits) {
  576. Console.WriteLine(d);
  577. }
  578. }
  579. [Category("Ordering Operators")]
  580. [Title("ThenBy - Comparer")]
  581. [Description("This sample uses an OrderBy and a ThenBy clause with a custom comparer to " +
  582. "sort first by word length and then by a case-insensitive sort of the words in an array.")]
  583. [LinkedClass("CaseInsensitiveComparer")]
  584. public void DataSetLinq36() {
  585. var words3 = testDS.Tables["Words3"].AsEnumerable();
  586. var sortedWords =
  587. words3.OrderBy(a => a.Field<string>("word").Length)
  588. .ThenBy(a => a.Field<string>("word"), new CaseInsensitiveComparer());
  589. foreach (var dr in sortedWords) {
  590. Console.WriteLine(dr["word"]);
  591. }
  592. }
  593. [Category("Ordering Operators")]
  594. [Title("ThenByDescending - Simple")]
  595. [Description("This sample uses a compound orderby to sort a list of products, " +
  596. "first by category, and then by unit price, from highest to lowest.")]
  597. public void DataSetLinq37() {
  598. var products = testDS.Tables["Products"].AsEnumerable();
  599. var sortedProducts =
  600. from p in products
  601. orderby p.Field<string>("Category"), p.Field<decimal>("UnitPrice") descending
  602. select p;
  603. foreach (var dr in sortedProducts) {
  604. Console.WriteLine(dr.Field<string>("ProductName"));
  605. }
  606. }
  607. [Category("Ordering Operators")]
  608. [Title("ThenByDescending - Comparer")]
  609. [Description("This sample uses an OrderBy and a ThenBy clause with a custom comparer to " +
  610. "sort first by word length and then by a case-insensitive descending sort " +
  611. "of the words in an array.")]
  612. [LinkedClass("CaseInsensitiveComparer")]
  613. public void DataSetLinq38() {
  614. var words3 = testDS.Tables["Words3"].AsEnumerable();
  615. var sortedWords =
  616. words3.OrderBy(a => a.Field<string>("word").Length)
  617. .ThenByDescending(a => a.Field<string>("word"), new CaseInsensitiveComparer());
  618. foreach (var dr in sortedWords){
  619. Console.WriteLine(dr.Field<string>("word"));
  620. }
  621. }
  622. [Category("Ordering Operators")]
  623. [Title("Reverse")]
  624. [Description("This sample uses Reverse to create a list of all digits in the array whose " +
  625. "second letter is 'i' that is reversed from the order in the original array.")]
  626. public void DataSetLinq39() {
  627. var digits = testDS.Tables["Digits"].AsEnumerable();
  628. var reversedIDigits = (
  629. from d in digits
  630. where d.Field<string>("digit")[1] == 'i'
  631. select d).Reverse();
  632. Console.WriteLine("A backwards list of the digits with a second character of 'i':");
  633. foreach (var d in reversedIDigits) {
  634. Console.WriteLine(d.Field<string>("digit"));
  635. }
  636. }
  637. [Category("Grouping Operators")]
  638. [Title("GroupBy - Simple 1")]
  639. [Description("This sample uses group by to partition a list of numbers by " +
  640. "their remainder when divided by 5.")]
  641. public void DataSetLinq40() {
  642. var numbers = testDS.Tables["Numbers"].AsEnumerable();
  643. var numberGroups =
  644. from n in numbers
  645. group n by n.Field<int>("number") % 5 into g
  646. select new {Remainder = g.Key, Numbers = g};
  647. foreach (var g in numberGroups) {
  648. Console.WriteLine("Numbers with a remainder of {0} when divided by 5:", g.Remainder);
  649. foreach (var n in g.Numbers) {
  650. Console.WriteLine(n.Field<int>("number"));
  651. }
  652. }
  653. }
  654. [Category("Grouping Operators")]
  655. [Title("GroupBy - Simple 2")]
  656. [Description("This sample uses group by to partition a list of words by " +
  657. "their first letter.")]
  658. public void DataSetLinq41() {
  659. var words4 = testDS.Tables["Words4"].AsEnumerable();
  660. var wordGroups =
  661. from w in words4
  662. group w by w.Field<string>("word")[0] into g
  663. select new {FirstLetter = g.Key, Words = g};
  664. foreach (var g in wordGroups) {
  665. Console.WriteLine("Words that start with the letter '{0}':", g.FirstLetter);
  666. foreach (var w in g.Words) {
  667. Console.WriteLine(w.Field<string>("word"));
  668. }
  669. }
  670. }
  671. [Category("Grouping Operators")]
  672. [Title("GroupBy - Simple 3")]
  673. [Description("This sample uses group by to partition a list of products by category.")]
  674. public void DataSetLinq42() {
  675. var products = testDS.Tables["Products"].AsEnumerable();
  676. var productGroups =
  677. from p in products
  678. group p by p.Field<string>("Category") into g
  679. select new {Category = g.Key, Products = g};
  680. foreach (var g in productGroups) {
  681. Console.WriteLine("Category: {0}", g.Category);
  682. foreach (var w in g.Products) {
  683. Console.WriteLine("\t" + w.Field<string>("ProductName"));
  684. }
  685. }
  686. }
  687. [Category("Grouping Operators")]
  688. [Title("GroupBy - Nested")]
  689. [Description("This sample uses group by to partition a list of each customer's orders, " +
  690. "first by year, and then by month.")]
  691. public void DataSetLinq43() {
  692. var customers = testDS.Tables["Customers"].AsEnumerable();
  693. var customerOrderGroups =
  694. from c in customers
  695. select
  696. new {CompanyName = c.Field<string>("CompanyName"),
  697. YearGroups =
  698. from o in c.GetChildRows("CustomersOrders")
  699. group o by o.Field<DateTime>("OrderDate").Year into yg
  700. select
  701. new {Year = yg.Key,
  702. MonthGroups =
  703. from o in yg
  704. group o by o.Field<DateTime>("OrderDate").Month into mg
  705. select new {Month = mg.Key, Orders = mg}
  706. }
  707. };
  708. foreach(var cog in customerOrderGroups) {
  709. Console.WriteLine("CompanyName= {0}", cog.CompanyName);
  710. foreach(var yg in cog.YearGroups) {
  711. Console.WriteLine("\t Year= {0}", yg.Year);
  712. foreach(var mg in yg.MonthGroups) {
  713. Console.WriteLine("\t\t Month= {0}", mg.Month);
  714. foreach(var order in mg.Orders) {
  715. Console.WriteLine("\t\t\t OrderID= {0} ", order.Field<int>("OrderID"));
  716. Console.WriteLine("\t\t\t OrderDate= {0} ", order.Field<DateTime>("OrderDate"));
  717. }
  718. }
  719. }
  720. }
  721. }
  722. private class AnagramEqualityComparer : IEqualityComparer<string>
  723. {
  724. public bool Equals(string x, string y) {
  725. return getCanonicalString(x) == getCanonicalString(y);
  726. }
  727. public int GetHashCode(string obj) {
  728. return getCanonicalString(obj).GetHashCode();
  729. }
  730. private string getCanonicalString(string word) {
  731. char[] wordChars = word.ToCharArray();
  732. Array.Sort<char>(wordChars);
  733. return new string(wordChars);
  734. }
  735. }
  736. [Category("Grouping Operators")]
  737. [Title("GroupBy - Comparer")]
  738. [Description("This sample uses GroupBy to partition trimmed elements of an array using " +
  739. "a custom comparer that matches words that are anagrams of each other.")]
  740. [LinkedClass("AnagramEqualityComparer")]
  741. public void DataSetLinq44() {
  742. var anagrams = testDS.Tables["Anagrams"].AsEnumerable();
  743. var orderGroups = anagrams.GroupBy(w => w.Field<string>("anagram").Trim(), new AnagramEqualityComparer());
  744. foreach (var g in orderGroups) {
  745. Console.WriteLine("Key: {0}", g.Key);
  746. foreach (var w in g) {
  747. Console.WriteLine("\t" + w.Field<string>("anagram"));
  748. }
  749. }
  750. }
  751. [Category("Grouping Operators")]
  752. [Title("GroupBy - Comparer, Mapped")]
  753. [Description("This sample uses GroupBy to partition trimmed elements of an array using " +
  754. "a custom comparer that matches words that are anagrams of each other, " +
  755. "and then converts the results to uppercase.")]
  756. [LinkedClass("AnagramEqualityComparer")]
  757. public void DataSetLinq45() {
  758. var anagrams = testDS.Tables["Anagrams"].AsEnumerable();
  759. var orderGroups = anagrams.GroupBy(
  760. w => w.Field<string>("anagram").Trim(),
  761. a => a.Field<string>("anagram").ToUpper(),
  762. new AnagramEqualityComparer()
  763. );
  764. foreach (var g in orderGroups) {
  765. Console.WriteLine("Key: {0}", g.Key);
  766. foreach (var w in g) {
  767. Console.WriteLine("\t" + w);
  768. }
  769. }
  770. }
  771. #endregion
  772. #region "Set Operators"
  773. [Category("Set Operators")]
  774. [Title("Distinct - 1")]
  775. [Description("This sample uses Distinct to remove duplicate elements in a sequence of " +
  776. "factors of 300.")]
  777. public void DataSetLinq46() {
  778. var factorsOf300 = testDS.Tables["FactorsOf300"].AsEnumerable();
  779. var uniqueFactors = factorsOf300.Distinct(DataRowComparer.Default);
  780. Console.WriteLine("Prime factors of 300:");
  781. foreach (var f in uniqueFactors) {
  782. Console.WriteLine(f.Field<int>("factor"));
  783. }
  784. }
  785. [Category("Set Operators")]
  786. [Title("Distinct - 2")]
  787. [Description("This sample uses Distinct to find unique employees")]
  788. public void DataSetLinq47() {
  789. var employees1 = testDS.Tables["employees1"].AsEnumerable();
  790. var employees = employees1.Distinct(DataRowComparer.Default);
  791. foreach (var row in employees) {
  792. Console.WriteLine("Id: {0} LastName: {1} Level: {2}", row[0], row[1], row[2]);
  793. }
  794. }
  795. [Category("Set Operators")]
  796. [Title("Union - 1")]
  797. [Description("This sample uses Union to create one sequence that contains the unique values " +
  798. "from both arrays.")]
  799. public void DataSetLinq48() {
  800. var numbersA = testDS.Tables["NumbersA"].AsEnumerable();
  801. var numbersB = testDS.Tables["NumbersB"].AsEnumerable();
  802. var uniqueNumbers = numbersA.Union(numbersB.AsEnumerable(), DataRowComparer.Default);
  803. Console.WriteLine("Unique numbers from both arrays:");
  804. foreach (var n in uniqueNumbers) {
  805. Console.WriteLine(n.Field<int>("number"));
  806. }
  807. }
  808. [Category("Set Operators")]
  809. [Title("Union - 2")]
  810. [Description("This sample uses Union to create one sequence based on two DataTables.")]
  811. public void DataSetLinq49() {
  812. var employees1 = testDS.Tables["employees1"].AsEnumerable();
  813. var employees2 = testDS.Tables["employees2"].AsEnumerable();
  814. var employees = employees1.Union(employees2, DataRowComparer.Default);
  815. Console.WriteLine("Union of employees tables");
  816. foreach (var row in employees) {
  817. Console.WriteLine("Id: {0} LastName: {1} Level: {2}", row[0], row[1], row[2]);
  818. }
  819. }
  820. [Category("Set Operators")]
  821. [Title("Intersect - 1")]
  822. [Description("This sample uses Intersect to create one sequence that contains the common values " +
  823. "shared by both arrays.")]
  824. public void DataSetLinq50() {
  825. var numbersA = testDS.Tables["NumbersA"].AsEnumerable();
  826. var numbersB = testDS.Tables["NumbersB"].AsEnumerable();
  827. var commonNumbers = numbersA.Intersect(numbersB, DataRowComparer.Default);
  828. Console.WriteLine("Common numbers shared by both arrays:");
  829. foreach (var n in commonNumbers) {
  830. Console.WriteLine(n.Field<int>(0));
  831. }
  832. }
  833. [Category("Set Operators")]
  834. [Title("Intersect - 2")]
  835. [Description("This sample uses Intersect to create one sequence based on two DataTables.")]
  836. public void DataSetLinq51() {
  837. var employees1 = testDS.Tables["employees1"].AsEnumerable();
  838. var employees2 = testDS.Tables["employees2"].AsEnumerable();
  839. var employees = employees1.Intersect(employees2, DataRowComparer.Default);
  840. Console.WriteLine("Intersect of employees tables");
  841. foreach (var row in employees) {
  842. Console.WriteLine("Id: {0} LastName: {1} Level: {2}", row[0], row[1], row[2]);
  843. }
  844. }
  845. [Category("Set Operators")]
  846. [Title("Except - 1")]
  847. [Description("This sample uses Except to create a sequence that contains the values from numbersA" +
  848. "that are not also in numbersB.")]
  849. public void DataSetLinq52() {
  850. var numbersA = testDS.Tables["NumbersA"].AsEnumerable();
  851. var numbersB = testDS.Tables["NumbersB"].AsEnumerable();
  852. var aOnlyNumbers = numbersA.Except(numbersB, DataRowComparer.Default);
  853. Console.WriteLine("Numbers in first array but not second array:");
  854. foreach (var n in aOnlyNumbers) {
  855. Console.WriteLine(n["number"]);
  856. }
  857. }
  858. [Category("Set Operators")]
  859. [Title("Except - 2")]
  860. [Description("This sample uses Except to create one sequence based on two DataTables.")]
  861. public void DataSetLinq53() {
  862. var employees1 = testDS.Tables["employees1"].AsEnumerable();
  863. var employees2 = testDS.Tables["employees2"].AsEnumerable();
  864. var employees = employees1.Except(employees2, DataRowComparer.Default);
  865. Console.WriteLine("Except of employees tables");
  866. foreach (var row in employees) {
  867. Console.WriteLine("Id: {0} LastName: {1} Level: {2}", row[0], row[1], row[2]);
  868. }
  869. }
  870. #endregion
  871. #region "Conversion Operators"
  872. [Category("Conversion Operators")]
  873. [Title("ToArray")]
  874. [Description("This sample uses ToArray to immediately evaluate a sequence into an array.")]
  875. public void DataSetLinq54() {
  876. var doubles = testDS.Tables["Doubles"].AsEnumerable();
  877. var doublesArray = doubles.ToArray();
  878. var sortedDoubles =
  879. from d in doublesArray
  880. orderby d.Field<double>("double") descending
  881. select d;
  882. Console.WriteLine("Every double from highest to lowest:");
  883. foreach (var d in sortedDoubles) {
  884. Console.WriteLine(d.Field<double>("double"));
  885. }
  886. }
  887. [Category("Conversion Operators")]
  888. [Title("ToList")]
  889. [Description("This sample uses ToList to immediately evaluate a sequence into a List<T>.")]
  890. public void DataSetLinq55() {
  891. var words = testDS.Tables["Words"].AsEnumerable();
  892. var wordList = words.ToList();
  893. var sortedWords =
  894. from w in wordList
  895. orderby w.Field<string>("word")
  896. select w;
  897. Console.WriteLine("The sorted word list:");
  898. foreach (var w in sortedWords) {
  899. Console.WriteLine(w.Field<string>("word").ToLower());
  900. }
  901. }
  902. [Category("Conversion Operators")]
  903. [Title("ToDictionary")]
  904. [Description("This sample uses ToDictionary to immediately evaluate a sequence and a " +
  905. "related key expression into a dictionary.")]
  906. public void DataSetLinq56() {
  907. var scoreRecords = testDS.Tables["ScoreRecords"].AsEnumerable();
  908. var scoreRecordsDict = scoreRecords.ToDictionary(sr => sr.Field<string>("Name"));
  909. Console.WriteLine("Bob's score: {0}", scoreRecordsDict["Bob"]["Score"]);
  910. }
  911. [Category("Conversion Operators")]
  912. [Title("OfType")]
  913. [Description("This sample uses OfType to return to return IEnumerable<DataRow>")]
  914. public void DataSetLinq57() {
  915. DataTable numbers = testDS.Tables["Numbers"];
  916. var rows = numbers.Rows.OfType<DataRow>();
  917. foreach (DataRow d in rows) {
  918. Console.WriteLine(d.Field<int>("number"));
  919. }
  920. }
  921. #endregion
  922. #region "Element Operators"
  923. [Category("Element Operators")]
  924. [Title("First - Simple")]
  925. [Description("This sample uses First to return the first matching element " +
  926. "as a Product, instead of as a sequence containing a Product.")]
  927. public void DataSetLinq58() {
  928. var products = testDS.Tables["Products"].AsEnumerable();
  929. DataRow product12 = (
  930. from p in products
  931. where (int)p["ProductID"] == 12
  932. select p )
  933. .First();
  934. Console.WriteLine("ProductId: " + product12.Field<int>("ProductId"));
  935. Console.WriteLine("ProductName: " + product12.Field<string>("ProductName"));
  936. }
  937. [Category("Element Operators")]
  938. [Title("First - Condition")]
  939. [Description("This sample uses First to find the first element in the array that starts with 'o'.")]
  940. public void DataSetLinq59() {
  941. var digits = testDS.Tables["Digits"].AsEnumerable();
  942. var startsWithO = digits.First(s => s.Field<string>("digit")[0] == 'o');
  943. Console.WriteLine("A string starting with 'o': {0}", startsWithO.Field<string>("digit"));
  944. }
  945. [Category("Element Operators")]
  946. [Title("ElementAt")]
  947. [Description("This sample uses ElementAt to retrieve the second number greater than 5 " +
  948. "from an array.")]
  949. public void DataSetLinq64() {
  950. var numbers = testDS.Tables["Numbers"].AsEnumerable();
  951. var fourthLowNum = (
  952. from n in numbers
  953. where n.Field<int>("number") > 5
  954. select n.Field<int>("number"))
  955. .ElementAt(3); // 3 because sequences use 0-based indexing
  956. Console.WriteLine("Second number > 5: {0}", fourthLowNum);
  957. }
  958. [Category("Element Operators")]
  959. [Title("Def…

Large files files are truncated, but you can click here to view the full file