PageRenderTime 54ms CodeModel.GetById 9ms RepoModel.GetById 1ms app.codeStats 0ms

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

#
C# | 2574 lines | 2010 code | 550 blank | 14 comment | 42 complexity | ad57c51159d7888f3b8e3afe5e382f71 MD5 | raw 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("Default If Empty")]
  960. [Description("")]
  961. public void DataSetLinq105() {
  962. //create an empty table
  963. var emptyTable = new DataTable("EmptyTable").AsEnumerable();
  964. DataTable numbers = testDS.Tables["Numbers"];
  965. //create a default row
  966. DataRow defaultRow = numbers.NewRow();
  967. defaultRow["number"] = 101;
  968. var defaultRowSequence = emptyTable.DefaultIfEmpty(defaultRow);
  969. foreach(DataRow row in defaultRowSequence) {
  970. Console.WriteLine(row.Field<int>("number"));
  971. }
  972. }
  973. #endregion
  974. #region "Generation Operators"
  975. [Category("Generation Operators")]
  976. [Title("Range")]
  977. [Description("This sample uses Range to generate a sequence of numbers from 100 to 149 " +
  978. "that is used to find which numbers in that range are odd and even.")]
  979. public void DataSetLinq65() {
  980. var numbers =
  981. from n in Enumerable.Range(100, 50)
  982. select new {Number = n, OddEven = n % 2 == 1 ? "odd" : "even"};
  983. foreach (var n in numbers) {
  984. Console.WriteLine("The number {0} is {1}.", n.Number, n.OddEven);
  985. }
  986. }
  987. [Category("Generation Operators")]
  988. [Title("Repeat")]
  989. [Description("This sample uses Repeat to generate a sequence that contains the number 7 ten times.")]
  990. public void DataSetLinq66() {
  991. var numbers = Enumerable.Repeat(7, 10);
  992. foreach (var n in numbers) {
  993. Console.WriteLine(n);
  994. }
  995. }
  996. #endregion
  997. #region "Quantifiers"
  998. [Category("Quantifiers")]
  999. [Title("Any - Simple")]
  1000. [Description("This sample uses Any to determine if any of the words in the array " +
  1001. "contain the substring 'ei'.")]
  1002. public void DataSetLinq67() {
  1003. var words2 = testDS.Tables["Words2"].AsEnumerable();
  1004. bool iAfterE = words2.Any(w => w.Field<string>("word").Contains("ei"));
  1005. Console.WriteLine("There is a word that contains in the list that contains 'ei': {0}", iAfterE);
  1006. }
  1007. [Category("Quantifiers")]
  1008. [Title("Any - Grouped")]
  1009. [Description("This sample uses Any to return a grouped a list of products only for categories " +
  1010. "that have at least one product that is out of stock.")]
  1011. public void DataSetLinq69() {
  1012. var products = testDS.Tables["Products"].AsEnumerable();
  1013. var productGroups =
  1014. from p in products
  1015. group p by p.Field<string>("Category") into g
  1016. where g.Any(p => p.Field<int>("UnitsInStock") == 0)
  1017. select new {Category = g.Key, Products = g};
  1018. foreach(var pg in productGroups) {
  1019. Console.WriteLine(pg.Category);
  1020. foreach(var p in pg.Products) {
  1021. Console.WriteLine("\t" + p.Field<string>("ProductName"));
  1022. }
  1023. }
  1024. }
  1025. [Category("Quantifiers")]
  1026. [Title("All - Simple")]
  1027. [Description("This sample uses All to determine whether an array contains " +
  1028. "only odd numbers.")]
  1029. public void DataSetLinq70() {
  1030. var numbers = testDS.Tables["Numbers"].AsEnumerable();
  1031. bool onlyOdd = numbers.All(n => n.Field<int>("number") % 2 == 1);
  1032. Console.WriteLine("The list contains only odd numbers: {0}", onlyOdd);
  1033. }
  1034. [Category("Quantifiers")]
  1035. [Title("All - Grouped")]
  1036. [Description("This sample uses All to return a grouped a list of products only for categories " +
  1037. "that have all of their products in stock.")]
  1038. public void DataSetLinq72() {
  1039. var products = testDS.Tables["Products"].AsEnumerable();
  1040. var productGroups =
  1041. from p in products
  1042. group p by p.Field<string>("Category") into g
  1043. where g.All(p => p.Field<int>("UnitsInStock") > 0)
  1044. select new {Category = g.Key, Products = g};
  1045. foreach(var pg in productGroups) {
  1046. Console.WriteLine(pg.Category);
  1047. foreach(var p in pg.Products) {
  1048. Console.WriteLine("\t" + p.Field<string>("ProductName"));
  1049. }
  1050. }
  1051. }
  1052. [Category("Quantifiers")]
  1053. [Title("Contains")]
  1054. [Description("")]
  1055. public void DataSetLinq102() {
  1056. var numbers = testDS.Tables["Numbers"];
  1057. //Find DataRow with number == 3
  1058. DataRow rowToFind = null;
  1059. foreach(DataRow r in numbers.Rows) {
  1060. if (r.Field<int>("number") == 3) {
  1061. rowToFind = r;
  1062. break;
  1063. }
  1064. }
  1065. var foundRow = numbers.AsEnumerable().Contains(rowToFind);
  1066. Console.WriteLine("Found Row: {0}", foundRow);
  1067. }
  1068. #endregion
  1069. #region "Aggregate Operators"
  1070. [Category("Aggregate Operators")]
  1071. [Title("Count - Simple")]
  1072. [Description("This sample uses Count to get the number of unique factors of 300.")]
  1073. public void DataSetLinq73() {
  1074. var factorsOf300 = testDS.Tables["FactorsOf300"].AsEnumerable();
  1075. int uniqueFactors = factorsOf300.Distinct().Count();
  1076. Console.WriteLine("There are {0} unique factors of 300.", uniqueFactors);
  1077. }
  1078. [Category("Aggregate Operators")]
  1079. [Title("Count - Conditional")]
  1080. [Description("This sample uses Count to get the number of odd ints in the array.")]
  1081. public void DataSetLinq74() {
  1082. var numbers = testDS.Tables["Numbers"].AsEnumerable();
  1083. int oddNumbers = numbers.Count(n => n.Field<int>("number") % 2 == 1);
  1084. Console.WriteLine("There are {0} odd numbers in the list.", oddNumbers);
  1085. }
  1086. [Category("Aggregate Operators")]
  1087. [Title("Count - Nested")]
  1088. [Description("This sample uses Count to return a list of customers and how many orders " +
  1089. "each has.")]
  1090. public void DataSetLinq76() {
  1091. var customers = testDS.Tables["Customers"].AsEnumerable();
  1092. var orderCounts = from c in customers
  1093. where c.Field<string>("CustomerID") != "AAAAA"
  1094. select new {CustomerID = c.Field<string>("CustomerID"),
  1095. OrderCount = c.GetChildRows("CustomersOrders").Count()};
  1096. ObjectDumper.Write(orderCounts);
  1097. }
  1098. [Category("Aggregate Operators")]
  1099. [Title("Count - Grouped")]
  1100. [Description("This sample uses Count to return a list of categories and how many products " +
  1101. "each has.")]
  1102. public void DataSetLinq77() {
  1103. var products = testDS.Tables["Products"].AsEnumerable();
  1104. var categoryCounts =
  1105. from p in products
  1106. group p by p.Field<string>("Category") into g
  1107. select new {Category = g.Key, ProductCount = g.Count()};
  1108. ObjectDumper.Write(categoryCounts);
  1109. }
  1110. [Category("Aggregate Operators")]
  1111. [Title("Long Count Simple")]
  1112. [Description("Gets the count as a long")]
  1113. public void DataSetLinq103() {
  1114. var products = testDS.Tables["Products"].AsEnumerable();
  1115. long numberOfProducts = products.LongCount();
  1116. Console.WriteLine("There are {0} products", numberOfProducts);
  1117. }
  1118. [Category("Aggregate Operators")]
  1119. [Title("Long Count Conditional")]
  1120. [Description("This sample uses Count to get the number of odd ints in the array as a long")]
  1121. public void DataSetLinq104() {
  1122. var numbers = testDS.Tables["Numbers"].AsEnumerable();
  1123. long oddNumbers = numbers.LongCount(n => (int) n["number"] % 2 == 1);
  1124. Console.WriteLine("There are {0} odd numbers in the list.", oddNumbers);
  1125. }
  1126. [Category("Aggregate Operators")]
  1127. [Title("Sum - Projection")]
  1128. [Description("This sample uses Sum to get the total number of characters of all words " +
  1129. "in the array.")]
  1130. public void DataSetLinq79() {
  1131. var words = testDS.Tables["Words"].AsEnumerable();
  1132. double totalChars = words.Sum(w => w.Field<string>("word").Length);
  1133. Console.WriteLine("There are a total of {0} characters in these words.", totalChars);
  1134. }
  1135. [Category("Aggregate Operators")]
  1136. [Title("Sum - Grouped")]
  1137. [Description("This sample uses Sum to get the total units in stock for each product category.")]
  1138. public void DataSetLinq80() {
  1139. var products = testDS.Tables["Products"].AsEnumerable();
  1140. var categories =
  1141. from p in products
  1142. group p by p.Field<string>("Category") into g
  1143. select new {Category = g.Key, TotalUnitsInStock = g.Sum(p => p.Field<int>("UnitsInStock"))};
  1144. ObjectDumper.Write(categories);
  1145. }
  1146. [Category("Aggregate Operators")]
  1147. [Title("Min - Projection")]
  1148. [Description("This sample uses Min to get the length of the shortest word in an array.")]
  1149. public void DataSetLinq82() {
  1150. var words = testDS.Tables["Words"].AsEnumerable();
  1151. int shortestWord = words.Min(w => w.Field<string>("word").Length);
  1152. Console.WriteLine("The shortest word is {0} characters long.", shortestWord);
  1153. }
  1154. [Category("Aggregate Operators")]
  1155. [Title("Min - Grouped")]
  1156. [Description("This sample uses Min to get the cheapest price among each category's products.")]
  1157. public void DataSetLinq83() {
  1158. var products = testDS.Tables["Products"].AsEnumerable();
  1159. var categories =
  1160. from p in products
  1161. group p by p.Field<string>("Category") into g
  1162. select new {Category = g.Key, CheapestPrice = g.Min(p => p.Field<decimal>("UnitPrice"))};
  1163. ObjectDumper.Write(categories);
  1164. }
  1165. [Category("Aggregate Operators")]
  1166. [Title("Min - Elements")]
  1167. [Description("This sample uses Min to get the products with the cheapest price in each category.")]
  1168. public void DataSetLinq84() {
  1169. var products = testDS.Tables["Products"].AsEnumerable();
  1170. var categories =
  1171. from p in products
  1172. group p by p.Field<string>("Category") into g
  1173. let minPrice = g.Min(p => p.Field<decimal>("UnitPrice"))
  1174. select new {Category = g.Key, CheapestProducts = g.Where(p => p.Field<decimal>("UnitPrice") == minPrice)};
  1175. foreach (var g in categories) {
  1176. Console.WriteLine("Category: {0}", g.Category);
  1177. Console.WriteLine("CheapestProducts:");
  1178. foreach (var w in g.CheapestProducts) {
  1179. Console.WriteLine("\t" + w.Field<string>("ProductName"));
  1180. }
  1181. }
  1182. }
  1183. [Category("Aggregate Operators")]
  1184. [Title("Max - Projection")]
  1185. [Description("This sample uses Max to get the length of the longest word in an array.")]
  1186. public void DataSetLinq86() {
  1187. var words = testDS.Tables["Words"].AsEnumerable();
  1188. int longestLength = words.Max(w => w.Field<string>("word").Length);
  1189. Console.WriteLine("The longest word is {0} characters long.", longestLength);
  1190. }
  1191. [Category("Aggregate Operators")]
  1192. [Title("Max - Grouped")]
  1193. [Description("This sample uses Max to get the most expensive price among each category's products.")]
  1194. public void DataSetLinq87() {
  1195. var products = testDS.Tables["Products"].AsEnumerable();
  1196. var categories =
  1197. from p in products
  1198. group p by p.Field<string>("Category") into g
  1199. select new {Category = g.Key, MostExpensivePrice = g.Max(p => p.Field<decimal>("UnitPrice"))};
  1200. ObjectDumper.Write(categories);
  1201. }
  1202. [Category("Aggregate Operators")]
  1203. [Title("Max - Elements")]
  1204. [Description("This sample uses Max to get the products with the most expensive price in each category.")]
  1205. public void DataSetLinq88() {
  1206. var products = testDS.Tables["Products"].AsEnumerable();
  1207. var categories =
  1208. from p in products
  1209. group p by p.Field<string>("Category") into g
  1210. let maxPrice = g.Max(p => p.Field<decimal>("UnitPrice"))
  1211. select new {Category = g.Key, MostExpensiveProducts = g.Where(p => p.Field<decimal>("UnitPrice")== maxPrice)};
  1212. foreach (var g in categories) {
  1213. Console.WriteLine("Category: {0}", g.Category);
  1214. Console.WriteLine("MostExpensiveProducts:");
  1215. foreach (var w in g.MostExpensiveProducts) {
  1216. Console.WriteLine("\t" + w.Field<string>("ProductName"));
  1217. }
  1218. }
  1219. }
  1220. [Category("Aggregate Operators")]
  1221. [Title("Average - Projection")]
  1222. [Description("This sample uses Average to get the average length of the words in the array.")]
  1223. public void DataSetLinq90() {
  1224. var words = testDS.Tables["Words"].AsEnumerable();
  1225. double averageLength = words.Average(w => w.Field<string>("word").Length);
  1226. Console.WriteLine("The average word length is {0} characters.", averageLength);
  1227. }
  1228. [Category("Aggregate Operators")]
  1229. [Title("Average - Grouped")]
  1230. [Description("This sample uses Average to get the average price of each category's products.")]
  1231. public void DataSetLinq91() {
  1232. var products = testDS.Tables["Products"].AsEnumerable();
  1233. var categories =
  1234. from p in products
  1235. group p by p.Field<string>("Category") into g
  1236. select new {Category = g.Key, AveragePrice = g.Average(p => p.Field<decimal>("UnitPrice"))};
  1237. ObjectDumper.Write(categories);
  1238. }
  1239. [Category("Aggregate Operators")]
  1240. [Title("Aggregate - Seed")]
  1241. [Description("This sample uses Aggregate to create a running account balance that " +
  1242. "subtracts each withdrawal from the initial balance of 100, as long as " +
  1243. "the balance never drops below 0.")]
  1244. public void DataSetLinq93() {
  1245. var attemptedWithdrawals = testDS.Tables["AttemptedWithdrawals"].AsEnumerable();
  1246. double startBalance = 100.0;
  1247. var endBalance =
  1248. attemptedWithdrawals.Aggregate(startBalance,
  1249. (balance, nextWithdrawal) =>
  1250. nextWithdrawal.Field<int>("withdrawal") <= balance ?
  1251. balance - nextWithdrawal.Field<int>("withdrawal") : balance);
  1252. Console.WriteLine("Ending balance: {0}", endBalance);
  1253. }
  1254. #endregion
  1255. #region "Miscellaneous Operators"
  1256. [Category("Miscellaneous Operators")]
  1257. [Title("Concat - 1")]
  1258. [Description("This sample uses Concat to create one sequence that contains each array's " +
  1259. "values, one after the other.")]
  1260. public void DataSetLinq94() {
  1261. var numbersA = testDS.Tables["NumbersA"].AsEnumerable();
  1262. var numbersB = testDS.Tables["NumbersB"].AsEnumerable();
  1263. var allNumbers = numbersA.Concat(numbersB);
  1264. Console.WriteLine("All numbers from both arrays:");
  1265. foreach (var n in allNumbers) {
  1266. Console.WriteLine(n.Field<int>("number"));
  1267. }
  1268. }
  1269. [Category("Miscellaneous Operators")]
  1270. [Title("Concat - 2")]
  1271. [Description("This sample uses Concat to create one sequence that contains the names of " +
  1272. "all customers and products, including any duplicates.")]
  1273. public void DataSetLinq95() {
  1274. var products = testDS.Tables["Products"].AsEnumerable();
  1275. var customers = testDS.Tables["Customers"].AsEnumerable();
  1276. var customerNames = customers.Select(r => r.Field<string>("CompanyName"));
  1277. var productNames = products.Select(r => r.Field<string>("ProductName"));
  1278. var allNames = customerNames.Concat(productNames);
  1279. Console.WriteLine("Customer and product names:");
  1280. foreach (var n in allNames) {
  1281. Console.WriteLine(n);
  1282. }
  1283. }
  1284. [Category("Miscellaneous Operators")]
  1285. [Title("SequenceEqual - 1")]
  1286. [Description("This sample uses SequenceEqual to see if two sequences match on all elements " +
  1287. "in the same order.")]
  1288. public void DataSetLinq96() {
  1289. var words = testDS.Tables["Words"].AsEnumerable();
  1290. bool match = words.SequenceEqual(words);
  1291. Console.WriteLine("The sequences match: {0}", match);
  1292. }
  1293. [Category("Miscellaneous Operators")]
  1294. [Title("SequenceEqual - 2")]
  1295. [Description("This sample uses SequenceEqual to see if two sequences match on all elements " +
  1296. "in different order.")]
  1297. public void DataSetLinq97() {
  1298. var words = testDS.Tables["Words"].AsEnumerable();
  1299. var words2 = testDS.Tables["Words2"].AsEnumerable();
  1300. bool match = words.SequenceEqual(words2);
  1301. Console.WriteLine("The sequences match: {0}", match);
  1302. }
  1303. [Category("Custom Sequence Operators")]
  1304. [Title("Combine")]
  1305. [Description("This sample uses a user-created sequence operator, Combine, to calculate the " +
  1306. "dot product of two vectors.")]
  1307. [LinkedClass("CustomSequenceOperators")]
  1308. public void DataSetLinq98() {
  1309. var numbersA = testDS.Tables["NumbersA"].AsEnumerable();
  1310. var numbersB = testDS.Tables["NumbersB"].AsEnumerable();
  1311. int dotProduct = numbersA.Combine(numbersB, (a, b) => a.Field<int>("number") * b.Field<int>("number")).Sum();
  1312. Console.WriteLine("Dot product: {0}", dotProduct);
  1313. }
  1314. [Category("Query Execution")]
  1315. [Title("ToLookup - element selector")]
  1316. [Description("The following sample shows how queries can be executed immediately with operators " +
  1317. "such as ToLookup().")]
  1318. public void DataSetLinq108() {
  1319. var products = testDS.Tables["Products"].AsEnumerable();
  1320. var productsLookup = products.ToLookup(p => p.Field<string>("Category"));
  1321. IEnumerable<DataRow> confections = productsLookup["Confections"];
  1322. Console.WriteLine("Number of categories: {0}", productsLookup.Count);
  1323. foreach(var product in confections) {
  1324. Console.WriteLine("ProductName: {0}", product.Field<string>("ProductName"));
  1325. }
  1326. }
  1327. [Category("Query Execution")]
  1328. [Title("Query Reuse")]
  1329. [Description("The following sample shows how, because of deferred execution, queries can be used " +
  1330. "again after data changes and will then operate on the new data.")]
  1331. public void DataSetLinq101() {
  1332. var numbers = testDS.Tables["Numbers"];
  1333. var lowNumbers =
  1334. from n in numbers.AsEnumerable()
  1335. where n.Field<int>("number") <= 3
  1336. select n;
  1337. Console.WriteLine("First run numbers <= 3:");
  1338. foreach (var n in lowNumbers) {
  1339. Console.WriteLine(n.Field<int>("number"));
  1340. }
  1341. for (int i = 0; i < 10; i++) {
  1342. numbers.Rows[i]["number"] = -(int)numbers.Rows[i]["number"];
  1343. }
  1344. // During this second run, the same query object,
  1345. // lowNumbers, will be iterating over the new state
  1346. // of numbers[], producing different results:
  1347. Console.WriteLine("Second run numbers <= 3:");
  1348. foreach (var n in lowNumbers) {
  1349. Console.WriteLine(n.Field<int>("number"));
  1350. }
  1351. //clean up numbers table
  1352. for (int i = 0; i < 10; i++) {
  1353. numbers.Rows[i]["number"] = -(int)numbers.Rows[i]["number"];
  1354. }
  1355. }
  1356. #endregion
  1357. #region "DataSet Loading examples"
  1358. [Category("DataSet Loading examples")]
  1359. [Title("Loading query results into a DataTable")]
  1360. [Description("Create and load a DataTable from a sequence")]
  1361. public void DataSetLinq109() {
  1362. var customers = testDS.Tables["Customers"].AsEnumerable();
  1363. var orders = testDS.Tables["Orders"].AsEnumerable();
  1364. var smallOrders =
  1365. from c in customers
  1366. from o in orders
  1367. where c.Field<string>("CustomerID") == o.Field<string>("CustomerID") &&
  1368. o.Field<decimal>("Total") < 500.00M
  1369. select new {CustomerID = (string) c["CustomerID"], OrderID = (int) o["OrderID"], Total = (decimal) o["Total"]};
  1370. DataTable myOrders = new DataTable();
  1371. myOrders.Columns.Add("CustomerID", typeof(string));
  1372. myOrders.Columns.Add("OrderID", typeof(int));
  1373. myOrders.Columns.Add("Total", typeof(decimal));
  1374. foreach (var result in smallOrders.Take(10))
  1375. {
  1376. myOrders.Rows.Add(new object[] { result.CustomerID, result.OrderID, result.Total });
  1377. }
  1378. PrettyPrintDataTable(myOrders);
  1379. }
  1380. [Category("DataSet Loading examples")]
  1381. [Title("Using CopyToDataTable")]
  1382. [Description("Load an existing DataTable with query results")]
  1383. public void DataSetLinq117a()
  1384. {
  1385. var customers = testDS.Tables["Customers"].AsEnumerable();
  1386. var orders = testDS.Tables["Orders"].AsEnumerable();
  1387. var query = from o in orders
  1388. where o.Field<decimal>("Total") < 500.00M
  1389. select o;
  1390. DataTable results = query.CopyToDataTable();
  1391. PrettyPrintDataTable(results);
  1392. }
  1393. private void PrettyPrintDataReader(DbDataReader reader) {
  1394. while(reader.Read()) {
  1395. StringBuilder sb = new StringBuilder();
  1396. for(int ii = 0; ii< reader.FieldCount; ii++) {
  1397. sb.AppendFormat("{0} = {1} ", reader.GetName(ii), reader.IsDBNull(ii) ? "null" : reader[ii]);
  1398. }
  1399. Console.WriteLine(sb.ToString());
  1400. }
  1401. }
  1402. private void PrettyPrintDataTable(DataTable table) {
  1403. Console.WriteLine("Table: {0}", table.TableName);
  1404. foreach(DataRow row in table.Rows) {
  1405. StringBuilder sb = new StringBuilder();
  1406. foreach(DataColumn dc in table.Columns) {
  1407. sb.AppendFormat("{0} = {1} ", dc.ColumnName, row.IsNull(dc) ? "null" : row[dc]);
  1408. }
  1409. Console.WriteLine(sb.ToString());
  1410. }
  1411. }
  1412. #endregion
  1413. #region "Linq over TypedDataSet"
  1414. [Category("LINQ over TypedDataSet")]
  1415. [Title("TypedDataSet - simple")]
  1416. [Description("Simple queries using typed dataset")]
  1417. public void DataSetLinq115() {
  1418. EmployeesTable employees = new EmployeesTable();
  1419. employees.AddEmployeesRow(5, "Jeff Jones", 60000);
  1420. employees.AddEmployeesRow(6, "Geoff Webber", 85000);
  1421. employees.AddEmployeesRow(7, "Alan Fox", 85000);
  1422. employees.AddEmployeesRow(8, "Dwight Schute", 101000);
  1423. employees.AddEmployeesRow(9, "Chaz Hoover", 99999);
  1424. var q = employees.Where(e => e.Salary >= 85000).OrderBy(e => e.Name);
  1425. foreach(var emp in q) {
  1426. Console.WriteLine("Id = {0}, Name = {1}", emp.ID, emp.Name);
  1427. }
  1428. }
  1429. [Category("LINQ over TypedDataSet")]
  1430. [Title("TypedDataSet - projection ")]
  1431. [Description("Projection using typed dataset")]
  1432. public void DataSetLinq116() {
  1433. EmployeesTable employees = new EmployeesTable();
  1434. employees.AddEmployeesRow(5, "Jeff Jones", 60000);
  1435. employees.AddEmployeesRow(6, "Geoff Webber", 85000);
  1436. employees.AddEmployeesRow(7, "Alan Fox", 85000);
  1437. employees.AddEmployeesRow(8, "Dwight Schute", 101000);
  1438. employees.AddEmployeesRow(9, "Chaz Hoover", 99999);
  1439. var q = employees.Select(emp => new {EmployeeID = emp.ID, EmployeeName = emp.Name, Employee = emp}).OrderBy(e => e.EmployeeName);
  1440. foreach(var o in q) {
  1441. Console.WriteLine("Id = {0}, Name = {1}", o.EmployeeID, o.EmployeeName);
  1442. }
  1443. }
  1444. [Category("LINQ over TypedDataSet")]
  1445. [Title("TypedDataSet - load DataTable ")]
  1446. [Description("Load an existing DataTable with query results")]
  1447. public void DataSetLinq117() {
  1448. EmployeesTable employees = new EmployeesTable();
  1449. employees.AddEmployeesRow(5, "Jeff Jones", 60000);
  1450. employees.AddEmployeesRow(6, "Geoff Webber", 85000);
  1451. employees.AddEmployeesRow(7, "Alan Fox", 85000);
  1452. employees.AddEmployeesRow(8, "Dwight Schute", 101000);
  1453. employees.AddEmployeesRow(9, "Chaz Hoover", 99999);
  1454. EmployeesTable filteredEmployees = new EmployeesTable();
  1455. var q = from e in employees
  1456. where e.ID > 7
  1457. select e;
  1458. q.CopyToDataTable(filteredEmployees, LoadOption.OverwriteChanges);
  1459. PrettyPrintDataTable(filteredEmployees);
  1460. }
  1461. #endregion
  1462. #region "Join Operators"
  1463. [Category("Join Operators")]
  1464. [Title("Join - simple")]
  1465. [Description("Simple join over two tables")]
  1466. public void DataSetLinq118() {
  1467. var customers = testDS.Tables["Customers"].AsEnumerable();
  1468. var orders = testDS.Tables["Orders"].AsEnumerable();
  1469. var smallOrders = customers.Join(orders, o => o.Field<string>("CustomerID"), c => c.Field<string>("CustomerID"),
  1470. (c, o) => new {CustomerID = c.Field<string>("CustomerID"), OrderID = o.Field<int>("OrderID"),
  1471. Total = o.Field<decimal>("Total")});
  1472. ObjectDumper.Write(smallOrders);
  1473. }
  1474. [Category("Join Operators")]
  1475. [Title("Join with grouped results")]
  1476. [Description("Join with grouped results")]
  1477. public void DataSetLinq119() {
  1478. var customers = testDS.Tables["Customers"].AsEnumerable();
  1479. var orders = testDS.Tables["Orders"].AsEnumerable();
  1480. var groupedOrders = customers.Join(orders, o => o.Field<string>("CustomerID"), c => c.Field<string>("CustomerID"),
  1481. (c, o) => new {CustomerID = c.Field<string>("CustomerID"), OrderID = o.Field<int>("OrderID"),
  1482. Total = o.Field<decimal>("Total")})
  1483. .GroupBy(r => r.OrderID);
  1484. foreach(var group in groupedOrders) {
  1485. foreach(var order in group) {
  1486. ObjectDumper.Write(order);
  1487. }
  1488. }
  1489. }
  1490. [Category("Join Operators")]
  1491. [Title("Group Join")]
  1492. [Description("Simple group join")]
  1493. public void DataSetLinq120() {
  1494. var customers = testDS.Tables["Customers"].AsEnumerable();
  1495. var orders = testDS.Tables["Orders"].AsEnumerable();
  1496. var q = from c in customers
  1497. join o in orders on c.Field<string>("CustomerID") equals o.Field<string>("CustomerID") into ords
  1498. select new {CustomerID = c.Field<string>("CustomerID"), ords=ords.Count()};
  1499. foreach(var r in q) {
  1500. Console.WriteLine("CustomerID: {0} Orders Count: {1}", r.CustomerID, r.ords);
  1501. }
  1502. }
  1503. #endregion
  1504. }
  1505. #region "Test Helper"
  1506. internal class TestHelper
  1507. {
  1508. //private readonly static string dataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), @"LINQ Preview\Data\");
  1509. // private readonly static string dataPath = @"F:\Dev\Feb CTP\Data";
  1510. private readonly static string dataPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @"..\..\Data\"));
  1511. internal static DataSet CreateTestDataset() {
  1512. DataSet ds = new DataSet();
  1513. // Customers Table
  1514. ds.Tables.Add(CreateNumbersTable());
  1515. ds.Tables.Add(CreateLowNumbersTable());
  1516. ds.Tables.Add(CreateEmptyNumbersTable());
  1517. ds.Tables.Add(CreateProductList());
  1518. ds.Tables.Add(CreateDigitsTable());
  1519. ds.Tables.Add(CreateWordsTable());
  1520. ds.Tables.Add(CreateWords2Table());
  1521. ds.Tables.Add(CreateWords3Table());
  1522. ds.Tables.Add(CreateWords4Table());
  1523. ds.Tables.Add(CreateAnagramsTable());
  1524. ds.Tables.Add(CreateNumbersATable());
  1525. ds.Tables.Add(CreateNumbersBTable());
  1526. ds.Tables.Add(CreateFactorsOf300());
  1527. ds.Tables.Add(CreateDoublesTable());
  1528. ds.Tables.Add(CreateScoreRecordsTable());
  1529. ds.Tables.Add(CreateAttemptedWithdrawalsTable());
  1530. ds.Tables.Add(CreateEmployees1Table());
  1531. ds.Tables.Add(CreateEmployees2Table());
  1532. CreateCustomersAndOrdersTables(ds);
  1533. ds.AcceptChanges();
  1534. return ds;
  1535. }
  1536. private static DataTable CreateNumbersTable() {
  1537. int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
  1538. DataTable table = new DataTable("Numbers");
  1539. table.Columns.Add("number", typeof(int));
  1540. foreach (int n in numbers) {
  1541. table.Rows.Add(new object[] {n});
  1542. }
  1543. return table;
  1544. }
  1545. private static DataTable CreateEmptyNumbersTable() {
  1546. DataTable table = new DataTable("EmptyNumbers");
  1547. table.Columns.Add("number", typeof(int));
  1548. return table;
  1549. }
  1550. private static DataTable CreateDigitsTable() {
  1551. string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
  1552. DataTable table = new DataTable("Digits");
  1553. table.Columns.Add("digit", typeof(string));
  1554. foreach (string digit in digits) {
  1555. table.Rows.Add(new object[] {digit});
  1556. }
  1557. return table;
  1558. }
  1559. private static DataTable CreateWordsTable() {
  1560. string[] words = { "aPPLE", "BlUeBeRrY", "cHeRry" };
  1561. DataTable table = new DataTable("Words");
  1562. table.Columns.Add("word", typeof(string));
  1563. foreach (string word in words) {
  1564. table.Rows.Add(new object[] {word});
  1565. }
  1566. return table;
  1567. }
  1568. private static DataTable CreateWords2Table() {
  1569. string[] words = { "believe", "relief", "receipt", "field" };
  1570. DataTable table = new DataTable("Words2");
  1571. table.Columns.Add("word", typeof(string));
  1572. foreach (string word in words) {
  1573. table.Rows.Add(new object[] {word});
  1574. }
  1575. return table;
  1576. }
  1577. private static DataTable CreateWords3Table() {
  1578. string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry"};
  1579. DataTable table = new DataTable("Words3");
  1580. table.Columns.Add("word", typeof(string));
  1581. foreach (string word in words) {
  1582. table.Rows.Add(new object[] {word});
  1583. }
  1584. return table;
  1585. }
  1586. private static DataTable CreateWords4Table() {
  1587. string[] words = { "blueberry", "chimpanzee", "abacus", "banana", "apple", "cheese" };
  1588. DataTable table = new DataTable("Words4");
  1589. table.Columns.Add("word", typeof(string));
  1590. foreach (string word in words) {
  1591. table.Rows.Add(new object[] {word});
  1592. }
  1593. return table;
  1594. }
  1595. private static DataTable CreateAnagramsTable() {
  1596. string[] anagrams = {"from ", " salt", " earn ", " last ", " near ", " form "};
  1597. DataTable table = new DataTable("Anagrams");
  1598. table.Columns.Add("anagram", typeof(string));
  1599. foreach (string word in anagrams) {
  1600. table.Rows.Add(new object[] {word});
  1601. }
  1602. return table;
  1603. }
  1604. private static DataTable CreateScoreRecordsTable() {
  1605. var scoreRecords = new [] { new {Name = "Alice", Score = 50},
  1606. new {Name = "Bob" , Score = 40},
  1607. new {Name = "Cathy", Score = 45}
  1608. };
  1609. DataTable table = new DataTable("ScoreRecords");
  1610. table.Columns.Add("Name", typeof(string));
  1611. table.Columns.Add("Score", typeof(int));
  1612. foreach (var r in scoreRecords) {
  1613. table.Rows.Add(new object[] {r.Name, r.Score});
  1614. }
  1615. return table;
  1616. }
  1617. private static DataTable CreateAttemptedWithdrawalsTable() {
  1618. int[] attemptedWithdrawals = { 20, 10, 40, 50, 10, 70, 30 };
  1619. DataTable table = new DataTable("AttemptedWithdrawals");
  1620. table.Columns.Add("withdrawal", typeof(int));
  1621. foreach (var r in attemptedWithdrawals) {
  1622. table.Rows.Add(new object[] {r});
  1623. }
  1624. return table;
  1625. }
  1626. private static DataTable CreateNumbersATable() {
  1627. int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
  1628. DataTable table = new DataTable("NumbersA");
  1629. table.Columns.Add("number", typeof(int));
  1630. foreach (int number in numbersA) {
  1631. table.Rows.Add(new object[] {number});
  1632. }
  1633. return table;
  1634. }
  1635. private static DataTable CreateNumbersBTable() {
  1636. int[] numbersB = { 1, 3, 5, 7, 8 };
  1637. DataTable table = new DataTable("NumbersB");
  1638. table.Columns.Add("number", typeof(int));
  1639. foreach (int number in numbersB) {
  1640. table.Rows.Add(new object[] {number});
  1641. }
  1642. return table;
  1643. }
  1644. private static DataTable CreateLowNumbersTable() {
  1645. int[] lowNumbers = { 1, 11, 3, 19, 41, 65, 19 };
  1646. DataTable table = new DataTable("LowNumbers");
  1647. table.Columns.Add("number", typeof(int));
  1648. foreach (int number in lowNumbers) {
  1649. table.Rows.Add(new object[] {number});
  1650. }
  1651. return table;
  1652. }
  1653. private static DataTable CreateFactorsOf300() {
  1654. int[] factorsOf300 = { 2, 2, 3, 5, 5 };
  1655. DataTable table = new DataTable("FactorsOf300");
  1656. table.Columns.Add("factor", typeof(int));
  1657. foreach (int factor in factorsOf300) {
  1658. table.Rows.Add(new object[] {factor});
  1659. }
  1660. return table;
  1661. }
  1662. private static DataTable CreateDoublesTable() {
  1663. double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 };
  1664. DataTable table = new DataTable("Doubles");
  1665. table.Columns.Add("double", typeof(double));
  1666. foreach (double d in doubles) {
  1667. table.Rows.Add(new object[] {d});
  1668. }
  1669. return table;
  1670. }
  1671. private static DataTable CreateEmployees1Table() {
  1672. DataTable table = new DataTable("Employees1");
  1673. table.Columns.Add("id", typeof(int));
  1674. table.Columns.Add("name", typeof(string));
  1675. table.Columns.Add("worklevel", typeof(int));
  1676. table.Rows.Add(new object[] {1, "Jones", 5});
  1677. table.Rows.Add(new object[] {2, "Smith", 5});
  1678. table.Rows.Add(new object[] {2, "Smith", 5});
  1679. table.Rows.Add(new object[] {3, "Smith", 6});
  1680. table.Rows.Add(new object[] {4, "Arthur", 11});
  1681. table.Rows.Add(new object[] {5, "Arthur", 12});
  1682. return table;
  1683. }
  1684. private static DataTable CreateEmployees2Table() {
  1685. DataTable table = new DataTable("Employees2");
  1686. table.Columns.Add("id", typeof(int));
  1687. table.Columns.Add("lastname", typeof(string));
  1688. table.Columns.Add("level", typeof(int));
  1689. table.Rows.Add(new object[] {1, "Jones", 10});
  1690. table.Rows.Add(new object[] {2, "Jagger", 5});
  1691. table.Rows.Add(new object[] {3, "Thomas", 6});
  1692. table.Rows.Add(new object[] {4, "Collins", 11});
  1693. table.Rows.Add(new object[] {4, "Collins", 12});
  1694. table.Rows.Add(new object[] {5, "Arthur", 12});
  1695. return table;
  1696. }
  1697. private static void CreateCustomersAndOrdersTables(DataSet ds) {
  1698. DataTable customers = new DataTable("Customers");
  1699. customers.Columns.Add("CustomerID", typeof(string));
  1700. customers.Columns.Add("CompanyName", typeof(string));
  1701. customers.Columns.Add("Address", typeof(string));
  1702. customers.Columns.Add("City", typeof(string));
  1703. customers.Columns.Add("Region", typeof(string));
  1704. customers.Columns.Add("PostalCode", typeof(string));
  1705. customers.Columns.Add("Country", typeof(string));
  1706. customers.Columns.Add("Phone", typeof(string));
  1707. customers.Columns.Add("Fax", typeof(string));
  1708. ds.Tables.Add(customers);
  1709. DataTable orders = new DataTable("Orders");
  1710. orders.Columns.Add("OrderID", typeof(int));
  1711. orders.Columns.Add("CustomerID", typeof(string));
  1712. orders.Columns.Add("OrderDate", typeof(DateTime));
  1713. orders.Columns.Add("Total", typeof(decimal));
  1714. ds.Tables.Add(orders);
  1715. DataRelation co = new DataRelation("CustomersOrders", customers.Columns["CustomerID"], orders.Columns["CustomerID"], true);
  1716. ds.Relations.Add(co);
  1717. string customerListPath = Path.GetFullPath(Path.Combine(dataPath, "customers.xml"));
  1718. var customerList = (
  1719. from e in XDocument.Load(customerListPath).
  1720. Root.Elements("customer")
  1721. select new Customer {
  1722. CustomerID = (string)e.Element("id"),
  1723. CompanyName = (string)e.Element("name"),
  1724. Address = (string)e.Element("address"),
  1725. City = (string)e.Element("city"),
  1726. Region = (string)e.Element("region"),
  1727. PostalCode = (string)e.Element("postalcode"),
  1728. Country = (string)e.Element("country"),
  1729. Phone = (string)e.Element("phone"),
  1730. Fax = (string)e.Element("fax"),
  1731. Orders = (
  1732. from o in e.Elements("orders").Elements("order")
  1733. select new Order {
  1734. OrderID = (int)o.Element("id"),
  1735. OrderDate = (DateTime)o.Element("orderdate"),
  1736. Total = (decimal)o.Element("total") } )
  1737. .ToArray() }
  1738. ).ToList();
  1739. foreach (Customer cust in customerList) {
  1740. customers.Rows.Add(new object[] {cust.CustomerID, cust.CompanyName, cust.Address, cust.City, cust.Region,
  1741. cust.PostalCode, cust.Country, cust.Phone, cust.Fax});
  1742. foreach (Order order in cust.Orders) {
  1743. orders.Rows.Add(new object[] {order.OrderID, cust.CustomerID, order.OrderDate, order.Total});
  1744. }
  1745. }
  1746. }
  1747. private static DataTable CreateProductList() {
  1748. DataTable table = new DataTable("Products");
  1749. table.Columns.Add("ProductID", typeof(int));
  1750. table.Columns.Add("ProductName", typeof(string));
  1751. table.Columns.Add("Category", typeof(string));
  1752. table.Columns.Add("UnitPrice", typeof(decimal));
  1753. table.Columns.Add("UnitsInStock", typeof(int));
  1754. var productList = new[] {
  1755. new { ProductID = 1, ProductName = "Chai", Category = "Beverages",
  1756. UnitPrice = 18.0000M, UnitsInStock = 39 },
  1757. new { ProductID = 2, ProductName = "Chang", Category = "Beverages",
  1758. UnitPrice = 19.0000M, UnitsInStock = 17 },
  1759. new { ProductID = 3, ProductName = "Aniseed Syrup", Category = "Condiments",
  1760. UnitPrice = 10.0000M, UnitsInStock = 13 },
  1761. new { ProductID = 4, ProductName = "Chef Anton's Cajun Seasoning", Category = "Condiments",
  1762. UnitPrice = 22.0000M, UnitsInStock = 53 },
  1763. new { ProductID = 5, ProductName = "Chef Anton's Gumbo Mix", Category = "Condiments",
  1764. UnitPrice = 21.3500M, UnitsInStock = 0 },
  1765. new { ProductID = 6, ProductName = "Grandma's Boysenberry Spread", Category = "Condiments",
  1766. UnitPrice = 25.0000M, UnitsInStock = 120 },
  1767. new { ProductID = 7, ProductName = "Uncle Bob's Organic Dried Pears", Category = "Produce",
  1768. UnitPrice = 30.0000M, UnitsInStock = 15 },
  1769. new { ProductID = 8, ProductName = "Northwoods Cranberry Sauce", Category = "Condiments",
  1770. UnitPrice = 40.0000M, UnitsInStock = 6 },
  1771. new { ProductID = 9, ProductName = "Mishi Kobe Niku", Category = "Meat/Poultry",
  1772. UnitPrice = 97.0000M, UnitsInStock = 29 },
  1773. new { ProductID = 10, ProductName = "Ikura", Category = "Seafood",
  1774. UnitPrice = 31.0000M, UnitsInStock = 31 },
  1775. new { ProductID = 11, ProductName = "Queso Cabrales", Category = "Dairy Products",
  1776. UnitPrice = 21.0000M, UnitsInStock = 22 },
  1777. new { ProductID = 12, ProductName = "Queso Manchego La Pastora", Category = "Dairy Products",
  1778. UnitPrice = 38.0000M, UnitsInStock = 86 },
  1779. new { ProductID = 13, ProductName = "Konbu", Category = "Seafood",
  1780. UnitPrice = 6.0000M, UnitsInStock = 24 },
  1781. new { ProductID = 14, ProductName = "Tofu", Category = "Produce",
  1782. UnitPrice = 23.2500M, UnitsInStock = 35 },
  1783. new { ProductID = 15, ProductName = "Genen Shouyu", Category = "Condiments",
  1784. UnitPrice = 15.5000M, UnitsInStock = 39 },
  1785. new { ProductID = 16, ProductName = "Pavlova", Category = "Confections",
  1786. UnitPrice = 17.4500M, UnitsInStock = 29 },
  1787. new { ProductID = 17, ProductName = "Alice Mutton", Category = "Meat/Poultry",
  1788. UnitPrice = 39.0000M, UnitsInStock = 0 },
  1789. new { ProductID = 18, ProductName = "Carnarvon Tigers", Category = "Seafood",
  1790. UnitPrice = 62.5000M, UnitsInStock = 42 },
  1791. new { ProductID = 19, ProductName = "Teatime Chocolate Biscuits", Category = "Confections",
  1792. UnitPrice = 9.2000M, UnitsInStock = 25 },
  1793. new { ProductID = 20, ProductName = "Sir Rodney's Marmalade", Category = "Confections",
  1794. UnitPrice = 81.0000M, UnitsInStock = 40 },
  1795. new { ProductID = 21, ProductName = "Sir Rodney's Scones", Category = "Confections",
  1796. UnitPrice = 10.0000M, UnitsInStock = 3 },
  1797. new { ProductID = 22, ProductName = "Gustaf's Knäckebröd", Category = "Grains/Cereals",
  1798. UnitPrice = 21.0000M, UnitsInStock = 104 },
  1799. new { ProductID = 23, ProductName = "Tunnbröd", Category = "Grains/Cereals",
  1800. UnitPrice = 9.0000M, UnitsInStock = 61 },
  1801. new { ProductID = 24, ProductName = "Guaraná Fantástica", Category = "Beverages",
  1802. UnitPrice = 4.5000M, UnitsInStock = 20 },
  1803. new { ProductID = 25, ProductName = "NuNuCa Nuß-Nougat-Creme", Category = "Confections",
  1804. UnitPrice = 14.0000M, UnitsInStock = 76 },
  1805. new { ProductID = 26, ProductName = "Gumbär Gummibärchen", Category = "Confections",
  1806. UnitPrice = 31.2300M, UnitsInStock = 15 },
  1807. new { ProductID = 27, ProductName = "Schoggi Schokolade", Category = "Confections",
  1808. UnitPrice = 43.9000M, UnitsInStock = 49 },
  1809. new { ProductID = 28, ProductName = "Rössle Sauerkraut", Category = "Produce",
  1810. UnitPrice = 45.6000M, UnitsInStock = 26 },
  1811. new { ProductID = 29, ProductName = "Thüringer Rostbratwurst", Category = "Meat/Poultry",
  1812. UnitPrice = 123.7900M, UnitsInStock = 0 },
  1813. new { ProductID = 30, ProductName = "Nord-Ost Matjeshering", Category = "Seafood",
  1814. UnitPrice = 25.8900M, UnitsInStock = 10 },
  1815. new { ProductID = 31, ProductName = "Gorgonzola Telino", Category = "Dairy Products",
  1816. UnitPrice = 12.5000M, UnitsInStock = 0 },
  1817. new { ProductID = 32, ProductName = "Mascarpone Fabioli", Category = "Dairy Products",
  1818. UnitPrice = 32.0000M, UnitsInStock = 9 },
  1819. new { ProductID = 33, ProductName = "Geitost", Category = "Dairy Products",
  1820. UnitPrice = 2.5000M, UnitsInStock = 112 },
  1821. new { ProductID = 34, ProductName = "Sasquatch Ale", Category = "Beverages",
  1822. UnitPrice = 14.0000M, UnitsInStock = 111 },
  1823. new { ProductID = 35, ProductName = "Steeleye Stout", Category = "Beverages",
  1824. UnitPrice = 18.0000M, UnitsInStock = 20 },
  1825. new { ProductID = 36, ProductName = "Inlagd Sill", Category = "Seafood",
  1826. UnitPrice = 19.0000M, UnitsInStock = 112 },
  1827. new { ProductID = 37, ProductName = "Gravad lax", Category = "Seafood",
  1828. UnitPrice = 26.0000M, UnitsInStock = 11 },
  1829. new { ProductID = 38, ProductName = "Côte de Blaye", Category = "Beverages",
  1830. UnitPrice = 263.5000M, UnitsInStock = 17 },
  1831. new { ProductID = 39, ProductName = "Chartreuse verte", Category = "Beverages",
  1832. UnitPrice = 18.0000M, UnitsInStock = 69 },
  1833. new { ProductID = 40, ProductName = "Boston Crab Meat", Category = "Seafood",
  1834. UnitPrice = 18.4000M, UnitsInStock = 123 },
  1835. new { ProductID = 41, ProductName = "Jack's New England Clam Chowder", Category = "Seafood",
  1836. UnitPrice = 9.6500M, UnitsInStock = 85 },
  1837. new { ProductID = 42, ProductName = "Singaporean Hokkien Fried Mee", Category = "Grains/Cereals",
  1838. UnitPrice = 14.0000M, UnitsInStock = 26 },
  1839. new { ProductID = 43, ProductName = "Ipoh Coffee", Category = "Beverages",
  1840. UnitPrice = 46.0000M, UnitsInStock = 17 },
  1841. new { ProductID = 44, ProductName = "Gula Malacca", Category = "Condiments",
  1842. UnitPrice = 19.4500M, UnitsInStock = 27 },
  1843. new { ProductID = 45, ProductName = "Rogede sild", Category = "Seafood",
  1844. UnitPrice = 9.5000M, UnitsInStock = 5 },
  1845. new { ProductID = 46, ProductName = "Spegesild", Category = "Seafood",
  1846. UnitPrice = 12.0000M, UnitsInStock = 95 },
  1847. new { ProductID = 47, ProductName = "Zaanse koeken", Category = "Confections",
  1848. UnitPrice = 9.5000M, UnitsInStock = 36 },
  1849. new { ProductID = 48, ProductName = "Chocolade", Category = "Confections",
  1850. UnitPrice = 12.7500M, UnitsInStock = 15 },
  1851. new { ProductID = 49, ProductName = "Maxilaku", Category = "Confections",
  1852. UnitPrice = 20.0000M, UnitsInStock = 10 },
  1853. new { ProductID = 50, ProductName = "Valkoinen suklaa", Category = "Confections",
  1854. UnitPrice = 16.2500M, UnitsInStock = 65 },
  1855. new { ProductID = 51, ProductName = "Manjimup Dried Apples", Category = "Produce",
  1856. UnitPrice = 53.0000M, UnitsInStock = 20 },
  1857. new { ProductID = 52, ProductName = "Filo Mix", Category = "Grains/Cereals",
  1858. UnitPrice = 7.0000M, UnitsInStock = 38 },
  1859. new { ProductID = 53, ProductName = "Perth Pasties", Category = "Meat/Poultry",
  1860. UnitPrice = 32.8000M, UnitsInStock = 0 },
  1861. new { ProductID = 54, ProductName = "Tourtičre", Category = "Meat/Poultry",
  1862. UnitPrice = 7.4500M, UnitsInStock = 21 },
  1863. new { ProductID = 55, ProductName = "Pâté chinois", Category = "Meat/Poultry",
  1864. UnitPrice = 24.0000M, UnitsInStock = 115 },
  1865. new { ProductID = 56, ProductName = "Gnocchi di nonna Alice", Category = "Grains/Cereals",
  1866. UnitPrice = 38.0000M, UnitsInStock = 21 },
  1867. new { ProductID = 57, ProductName = "Ravioli Angelo", Category = "Grains/Cereals",
  1868. UnitPrice = 19.5000M, UnitsInStock = 36 },
  1869. new { ProductID = 58, ProductName = "Escargots de Bourgogne", Category = "Seafood",
  1870. UnitPrice = 13.2500M, UnitsInStock = 62 },
  1871. new { ProductID = 59, ProductName = "Raclette Courdavault", Category = "Dairy Products",
  1872. UnitPrice = 55.0000M, UnitsInStock = 79 },
  1873. new { ProductID = 60, ProductName = "Camembert Pierrot", Category = "Dairy Products",
  1874. UnitPrice = 34.0000M, UnitsInStock = 19 },
  1875. new { ProductID = 61, ProductName = "Sirop d'érable", Category = "Condiments",
  1876. UnitPrice = 28.5000M, UnitsInStock = 113 },
  1877. new { ProductID = 62, ProductName = "Tarte au sucre", Category = "Confections",
  1878. UnitPrice = 49.3000M, UnitsInStock = 17 },
  1879. new { ProductID = 63, ProductName = "Vegie-spread", Category = "Condiments",
  1880. UnitPrice = 43.9000M, UnitsInStock = 24 },
  1881. new { ProductID = 64, ProductName = "Wimmers gute Semmelknödel", Category = "Grains/Cereals",
  1882. UnitPrice = 33.2500M, UnitsInStock = 22 },
  1883. new { ProductID = 65, ProductName = "Louisiana Fiery Hot Pepper Sauce", Category = "Condiments",
  1884. UnitPrice = 21.0500M, UnitsInStock = 76 },
  1885. new { ProductID = 66, ProductName = "Louisiana Hot Spiced Okra", Category = "Condiments",
  1886. UnitPrice = 17.0000M, UnitsInStock = 4 },
  1887. new { ProductID = 67, ProductName = "Laughing Lumberjack Lager", Category = "Beverages",
  1888. UnitPrice = 14.0000M, UnitsInStock = 52 },
  1889. new { ProductID = 68, ProductName = "Scottish Longbreads", Category = "Confections",
  1890. UnitPrice = 12.5000M, UnitsInStock = 6 },
  1891. new { ProductID = 69, ProductName = "Gudbrandsdalsost", Category = "Dairy Products",
  1892. UnitPrice = 36.0000M, UnitsInStock = 26 },
  1893. new { ProductID = 70, ProductName = "Outback Lager", Category = "Beverages",
  1894. UnitPrice = 15.0000M, UnitsInStock = 15 },
  1895. new { ProductID = 71, ProductName = "Flotemysost", Category = "Dairy Products",
  1896. UnitPrice = 21.5000M, UnitsInStock = 26 },
  1897. new { ProductID = 72, ProductName = "Mozzarella di Giovanni", Category = "Dairy Products",
  1898. UnitPrice = 34.8000M, UnitsInStock = 14 },
  1899. new { ProductID = 73, ProductName = "Röd Kaviar", Category = "Seafood",
  1900. UnitPrice = 15.0000M, UnitsInStock = 101 },
  1901. new { ProductID = 74, ProductName = "Longlife Tofu", Category = "Produce",
  1902. UnitPrice = 10.0000M, UnitsInStock = 4 },
  1903. new { ProductID = 75, ProductName = "Rhönbräu Klosterbier", Category = "Beverages",
  1904. UnitPrice = 7.7500M, UnitsInStock = 125 },
  1905. new { ProductID = 76, ProductName = "Lakkalikööri", Category = "Beverages",
  1906. UnitPrice = 18.0000M, UnitsInStock = 57 },
  1907. new { ProductID = 77, ProductName = "Original Frankfurter grüne Soße", Category = "Condiments",
  1908. UnitPrice = 13.0000M, UnitsInStock = 32 }
  1909. };
  1910. foreach (var x in productList) {
  1911. table.Rows.Add(new object[] {x.ProductID, x.ProductName, x.Category, x.UnitPrice, x.UnitsInStock});
  1912. }
  1913. return table;
  1914. }
  1915. }
  1916. public class Customer {
  1917. public Customer(string customerID, string companyName) {
  1918. CustomerID = customerID;
  1919. CompanyName = companyName;
  1920. Orders = new Order[10];
  1921. }
  1922. public Customer() {}
  1923. public string CustomerID;
  1924. public string CompanyName;
  1925. public string Address;
  1926. public string City;
  1927. public string Region;
  1928. public string PostalCode;
  1929. public string Country;
  1930. public string Phone;
  1931. public string Fax;
  1932. public Order[] Orders;
  1933. }
  1934. public class Order {
  1935. public Order(int orderID, DateTime orderDate, decimal total) {
  1936. OrderID = orderID;
  1937. OrderDate = orderDate;
  1938. Total = total;
  1939. }
  1940. public Order() {}
  1941. public int OrderID;
  1942. public DateTime OrderDate;
  1943. public decimal Total;
  1944. }
  1945. public class Pet {
  1946. private string name;
  1947. private string owner;
  1948. public string Name {
  1949. set {name = value;}
  1950. get {return name;}
  1951. }
  1952. public string Owner {
  1953. set {owner = value;}
  1954. get {return owner;}
  1955. }
  1956. }
  1957. public class Dog : Pet{
  1958. private string breed;
  1959. public string Breed {
  1960. set {breed = value;}
  1961. get {return breed;}
  1962. }
  1963. }
  1964. public class ShowDog : Dog{
  1965. private int ranking;
  1966. public int Ranking {
  1967. set {ranking = value;}
  1968. get {return ranking;}
  1969. }
  1970. }
  1971. public class EmployeesTable : TypedTableBase<EmployeesRow> {
  1972. public DataColumn ColumnId = new DataColumn("id", typeof(int));
  1973. public DataColumn ColumnName = new DataColumn("name", typeof(string));
  1974. public DataColumn ColumnSalary = new DataColumn("salary", typeof(decimal));
  1975. public EmployeesTable() {
  1976. this.TableName = "Employees";
  1977. this.Columns.Add(ColumnId);
  1978. this.Columns.Add(ColumnName);
  1979. this.Columns.Add(ColumnSalary);
  1980. this.AcceptChanges();
  1981. }
  1982. public EmployeesRow AddEmployeesRow(int id, string name, decimal salary) {
  1983. EmployeesRow rowEmployees = ((EmployeesRow)(this.NewRow()));
  1984. rowEmployees.ItemArray = new object[] {
  1985. id,
  1986. name,
  1987. salary};
  1988. this.Rows.Add(rowEmployees);
  1989. return rowEmployees;
  1990. }
  1991. protected override System.Data.DataRow NewRowFromBuilder(System.Data.DataRowBuilder builder) {
  1992. return new EmployeesRow(builder);
  1993. }
  1994. }
  1995. public class EmployeesRow : DataRow {
  1996. private EmployeesTable employeesTable;
  1997. public EmployeesRow(DataRowBuilder builder) : base(builder){this.employeesTable = ((EmployeesTable)this.Table); }
  1998. public int ID {
  1999. get {
  2000. return ((int)(this[employeesTable.ColumnId]));
  2001. }
  2002. set {
  2003. this[this.employeesTable.ColumnId] = value;
  2004. }
  2005. }
  2006. public decimal Salary {
  2007. get {
  2008. return ((decimal)(this[employeesTable.ColumnSalary]));
  2009. }
  2010. set {
  2011. this[this.employeesTable.ColumnSalary] = value;
  2012. }
  2013. }
  2014. public String Name {
  2015. get {
  2016. return ((string)(this[employeesTable.ColumnName]));
  2017. }
  2018. set {
  2019. this[this.employeesTable.ColumnName] = value;
  2020. }
  2021. }
  2022. }
  2023. #endregion
  2024. }