/EntityFramework/Beta1/LINQ101/C#/SampleQueries/DataSetLinqSamples.cs
C# | 2574 lines | 2010 code | 550 blank | 14 comment | 42 complexity | ad57c51159d7888f3b8e3afe5e382f71 MD5 | raw file
Large files files are truncated, but you can click here to view the full file
- //Copyright (C) Microsoft Corporation. All rights reserved.
-
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Data.Linq;
- using System.Data.Common;
- using System.Diagnostics;
- using System.Linq;
- using SampleSupport;
- using System.Xml.Linq;
- using System.Text;
- using System.IO;
- using System.Windows.Forms;
-
-
- // version erickt1
-
- namespace DataSetSampleQueries
- {
- public static class CustomSequenceOperators
- {
- public static IEnumerable<S> Combine<S>(this IEnumerable<DataRow> first, IEnumerable<DataRow> second, System.Linq.Func<DataRow, DataRow, S> func)
- {
- using (IEnumerator<DataRow> e1 = first.GetEnumerator(), e2 = second.GetEnumerator())
- {
- while (e1.MoveNext() && e2.MoveNext())
- {
- yield return func(e1.Current, e2.Current);
- }
- }
- }
- }
-
-
- [Title("101 LINQ over DataSet Samples")]
- [Prefix("DataSetLinq")]
- class DataSetLinqSamples : SampleHarness
- {
- private DataSet testDS;
-
- public DataSetLinqSamples() {
- testDS = TestHelper.CreateTestDataset();
- }
-
- #region "Restriction Operators"
-
- [Category("Restriction Operators")]
- [Title("Where - Simple 1")]
- [Description("This sample uses where to find all elements of an array less than 5.")]
- public void DataSetLinq1() {
-
- var numbers = testDS.Tables["Numbers"].AsEnumerable();
-
- var lowNums = from n in numbers
- where n.Field<int>("number") < 5
- select n;
-
- Console.WriteLine("Numbers < 5:");
- foreach (var x in lowNums) {
- Console.WriteLine(x[0]);
- }
- }
-
- [Category("Restriction Operators")]
- [Title("Where - Simple 2")]
- [Description("This sample uses where to find all products that are out of stock.")]
- public void DataSetLinq2() {
-
- var products = testDS.Tables["Products"].AsEnumerable();
-
- var soldOutProducts = from p in products
- where p.Field<int>("UnitsInStock") == 0
- select p;
-
- Console.WriteLine("Sold out products:");
- foreach (var product in soldOutProducts) {
- Console.WriteLine(product.Field<string>("ProductName") + " is sold out!");
- }
- }
-
- [Category("Restriction Operators")]
- [Title("Where - Simple 3")]
- [Description("This sample uses where to find all products that are in stock and " +
- "cost more than 3.00 per unit.")]
- public void DataSetLinq3() {
-
- var products = testDS.Tables["Products"].AsEnumerable();
-
- var expensiveInStockProducts = from p in products
- where p.Field<int>("UnitsInStock") > 0
- where p.Field<decimal>("UnitPrice") > 3.00M
- select p;
-
- Console.WriteLine("In-stock products that cost more than 3.00:");
- foreach (var product in expensiveInStockProducts) {
- Console.WriteLine(product.Field<string>("ProductName") + " is in stock and costs more than 3.00.");
- }
- }
-
- [Category("Restriction Operators")]
- [Title("Where - Drilldown")]
- [Description("This sample uses where to find all customers in Washington " +
- "and then uses the resulting sequence to drill down into their " +
- "orders.")]
- public void DataSetLinq4() {
-
- var customers = testDS.Tables["Customers"].AsEnumerable();
-
- var waCustomers =
- from c in customers
- where c.Field<string>("Region") == "WA"
- select c;
-
- Console.WriteLine("Customers from Washington and their orders:");
- foreach (var customer in waCustomers) {
- Console.WriteLine("Customer {0}: {1}", customer.Field<string>("CustomerID"), customer["CompanyName"]);
- foreach (var order in customer.GetChildRows("CustomersOrders")) {
- Console.WriteLine(" Order {0}: {1}", order["OrderID"], order["OrderDate"]);
- }
- }
-
-
- }
-
- [Category("Restriction Operators")]
- [Title("Where - Indexed")]
- [Description("This sample demonstrates an indexed Where clause that returns digits whose name is " +
- "shorter than their value.")]
- public void DataSetLinq5() {
-
- var digits = testDS.Tables["Digits"].AsEnumerable();
-
- var shortDigits = digits.Where((digit, index) => digit.Field<string>(0).Length < index);
-
- Console.WriteLine("Short digits:");
- foreach (var d in shortDigits) {
- Console.WriteLine("The word " + d["digit"] + " is shorter than its value.");
- }
- }
-
- [Category("Restriction Operators")]
- [Title("Single - Simple")]
- [Description("Turns a seqeunce into a single result")]
- public void DataSetLinq106() {
-
- //create an table with a single row
- var singleRowTable = new DataTable("SingleRowTable");
- singleRowTable.Columns.Add("id", typeof(int));
- singleRowTable.Rows.Add(new object[] {1});
-
- var singleRow = singleRowTable.AsEnumerable().Single();
-
- Console.WriteLine(singleRow != null);
- }
-
- [Category("Restriction Operators")]
- [Title("Single - with Predicate")]
- [Description("Returns a single element based on the specified predicate")]
- public void DataSetLinq107() {
-
- //create an table with a two rows
- var table = new DataTable("MyTable");
- table.Columns.Add("id", typeof(int));
- table.Rows.Add(new object[] {1});
- table.Rows.Add(new object[] {2});
-
- var singleRow = table.AsEnumerable().Single(r => r.Field<int>("id") == 1);
-
- Console.WriteLine(singleRow != null);
- }
-
- #endregion
-
- #region "Projection Operators"
-
- [Category("Projection Operators")]
- [Title("Select - Simple 1")]
- [Description("This sample uses select to produce a sequence of ints one higher than " +
- "those in an existing array of ints.")]
- public void DataSetLinq6() {
-
- var numbers = testDS.Tables["Numbers"].AsEnumerable();
-
- var numsPlusOne =
- from n in numbers
- select n.Field<int>(0) + 1;
-
- Console.WriteLine("Numbers + 1:");
- foreach (var i in numsPlusOne) {
- Console.WriteLine(i);
- }
- }
-
- [Category("Projection Operators")]
- [Title("Select - Simple 2")]
- [Description("This sample uses select to return a sequence of just the names of a list of products.")]
- public void DataSetLinq7() {
-
- var products = testDS.Tables["Products"].AsEnumerable();
-
- var productNames =
- from p in products
- select p.Field<string>("ProductName");
-
- Console.WriteLine("Product Names:");
- foreach (var productName in productNames) {
- Console.WriteLine(productName);
- }
- }
-
- [Category("Projection Operators")]
- [Title("Select - Transformation")]
- [Description("This sample uses select to produce a sequence of strings representing " +
- "the text version of a sequence of ints.")]
- public void DataSetLinq8() {
-
- var numbers = testDS.Tables["Numbers"].AsEnumerable();
- string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
-
- var textNums = numbers.Select(p => strings[p.Field<int>("number")]);
-
- Console.WriteLine("Number strings:");
- foreach (var s in textNums) {
- Console.WriteLine(s);
- }
- }
-
- [Category("Projection Operators")]
- [Title("Select - Anonymous Types 1")]
- [Description("This sample uses select to produce a sequence of the uppercase " +
- "and lowercase versions of each word in the original array.")]
- public void DataSetLinq9() {
-
- var words = testDS.Tables["Words"].AsEnumerable();
-
- var upperLowerWords = words.Select(p => new {Upper = (p.Field<string>(0)).ToUpper(),
- Lower = (p.Field<string>(0)).ToLower()});
-
- foreach (var ul in upperLowerWords) {
- Console.WriteLine("Uppercase: "+ ul.Upper + ", Lowercase: " + ul.Lower);
- }
- }
-
- [Category("Projection Operators")]
- [Title("Select - Anonymous Types 2")]
- [Description("This sample uses select to produce a sequence containing text " +
- "representations of digits and whether their length is even or odd.")]
- public void DataSetLinq10() {
-
- var numbers = testDS.Tables["Numbers"].AsEnumerable();
- var digits = testDS.Tables["Digits"];
- string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
-
- var digitOddEvens = numbers.
- Select(n => new {Digit = digits.Rows[n.Field<int>("number")]["digit"],
- Even = (n.Field<int>("number") % 2 == 0)});
-
- foreach (var d in digitOddEvens) {
- Console.WriteLine("The digit {0} is {1}.", d.Digit, d.Even ? "even" : "odd");
- }
- }
-
- [Category("Projection Operators")]
- [Title("Select - Anonymous Types 3")]
- [Description("This sample uses select to produce a sequence containing some properties " +
- "of Products, including UnitPrice which is renamed to Price " +
- "in the resulting type.")]
- public void DataSetLinq11() {
-
- var products = testDS.Tables["Products"].AsEnumerable();
-
- var productInfos = products.
- Select(n => new {ProductName = n.Field<string>("ProductName"),
- Category = n.Field<string>("Category"), Price = n.Field<decimal>("UnitPrice")});
-
- Console.WriteLine("Product Info:");
- foreach (var productInfo in productInfos) {
- Console.WriteLine("{0} is in the category {1} and costs {2} per unit.", productInfo.ProductName, productInfo.Category, productInfo.Price);
- }
- }
-
-
- [Category("Projection Operators")]
- [Title("Select - Indexed")]
- [Description("This sample uses an indexed Select clause to determine if the value of ints " +
- "in an array match their position in the array.")]
- public void DataSetLinq12() {
-
- var numbers = testDS.Tables["Numbers"].AsEnumerable();
-
- var numsInPlace = numbers.Select((num, index) => new {Num = num.Field<int>("number"),
- InPlace = (num.Field<int>("number") == index)});
-
- Console.WriteLine("Number: In-place?");
- foreach (var n in numsInPlace) {
- Console.WriteLine("{0}: {1}", n.Num, n.InPlace);
- }
- }
-
- [Category("Projection Operators")]
- [Title("Select - Filtered")]
- [Description("This sample combines select and where to make a simple query that returns " +
- "the text form of each digit less than 5.")]
- public void DataSetLinq13() {
-
- var numbers = testDS.Tables["Numbers"].AsEnumerable();
- var digits = testDS.Tables["Digits"];
-
- var lowNums =
- from n in numbers
- where n.Field<int>("number") < 5
- select digits.Rows[n.Field<int>("number")].Field<string>("digit");
-
- Console.WriteLine("Numbers < 5:");
- foreach (var num in lowNums) {
- Console.WriteLine(num);
- }
- }
-
- [Category("Projection Operators")]
- [Title("SelectMany - Compound from 1")]
- [Description("This sample uses a compound from clause to make a query that returns all pairs " +
- "of numbers from both arrays such that the number from numbersA is less than the number " +
- "from numbersB.")]
- public void DataSetLinq14() {
-
- var numbersA = testDS.Tables["NumbersA"].AsEnumerable();
- var numbersB = testDS.Tables["NumbersB"].AsEnumerable();
-
- var pairs =
- from a in numbersA
- from b in numbersB
- where a.Field<int>("number") < b.Field<int>("number")
- select new {a = a.Field<int>("number") , b = b.Field<int>("number")};
-
- Console.WriteLine("Pairs where a < b:");
- foreach (var pair in pairs) {
- Console.WriteLine("{0} is less than {1}", pair.a, pair.b);
- }
- }
-
- [Category("Projection Operators")]
- [Title("SelectMany - Compound from 2")]
- [Description("This sample uses a compound from clause to select all orders where the " +
- "order total is less than 500.00.")]
- public void DataSetLinq15() {
-
- var customers = testDS.Tables["Customers"].AsEnumerable();
- var orders = testDS.Tables["Orders"].AsEnumerable();
-
- var smallOrders =
- from c in customers
- from o in orders
- where c.Field<string>("CustomerID") == o.Field<string>("CustomerID")
- && o.Field<decimal>("Total") < 500.00M
- select new {CustomerID = c.Field<string>("CustomerID"), OrderID = o.Field<int>("OrderID"),
- Total = o.Field<decimal>("Total")};
-
- ObjectDumper.Write(smallOrders);
- }
-
- [Category("Projection Operators")]
- [Title("SelectMany - Compound from 3")]
- [Description("This sample uses a compound from clause to select all orders where the " +
- "order was made in 1998 or later.")]
- public void DataSetLinq16() {
-
- var customers = testDS.Tables["Customers"].AsEnumerable();
- var orders = testDS.Tables["Orders"].AsEnumerable();
-
- var myOrders =
- from c in customers
- from o in orders
- where c.Field<string>("CustomerID") == o.Field<string>("CustomerID") &&
- o.Field<DateTime>("OrderDate") >= new DateTime(1998, 1, 1)
- select new {CustomerID = c.Field<string>("CustomerID"), OrderID = o.Field<int>("OrderID"),
- OrderDate = o.Field<DateTime>("OrderDate")};
-
- ObjectDumper.Write(myOrders);
- }
-
- [Category("Projection Operators")]
- [Title("SelectMany - from Assignment")]
- [Description("This sample uses a compound from clause to select all orders where the " +
- "order total is greater than 2000.00 and uses from assignment to avoid " +
- "requesting the total twice.")]
- public void DataSetLinq17() {
-
- var customers = testDS.Tables["Customers"].AsEnumerable();
- var orders = testDS.Tables["Orders"].AsEnumerable();
-
- var myOrders =
- from c in customers
- from o in orders
- let total = o.Field<decimal>("Total")
- where c.Field<string>("CustomerID") == o.Field<string>("CustomerID")
- && total >= 2000.0M
- select new {CustomerID = c.Field<string>("CustomerID"), OrderID = o.Field<int>("OrderID"), total};
-
- ObjectDumper.Write(myOrders);
- }
-
- [Category("Projection Operators")]
- [Title("SelectMany - Multiple from")]
- [Description("This sample uses multiple from clauses so that filtering on customers can " +
- "be done before selecting their orders. This makes the query more efficient by " +
- "not selecting and then discarding orders for customers outside of Washington.")]
- public void DataSetLinq18() {
-
- var customers = testDS.Tables["Customers"].AsEnumerable();
- var orders = testDS.Tables["Orders"].AsEnumerable();
- DateTime cutoffDate = new DateTime(1997, 1, 1);
-
- var myOrders =
- from c in customers
- where c.Field<string>("Region") == "WA"
- from o in orders
- where c.Field<string>("CustomerID") == o.Field<string>("CustomerID")
- && (DateTime) o["OrderDate"] >= cutoffDate
- select new {CustomerID = c.Field<string>("CustomerID"), OrderID = o.Field<int>("OrderID")};
-
- ObjectDumper.Write(myOrders);
- }
-
- [Category("Projection Operators")]
- [Title("SelectMany - Indexed")]
- [Description("This sample uses an indexed SelectMany clause to select all orders, " +
- "while referring to customers by the order in which they are returned " +
- "from the query.")]
- public void DataSetLinq19() {
-
- var customers = testDS.Tables["Customers"].AsEnumerable();
- var orders = testDS.Tables["Orders"].AsEnumerable();
-
- var customerOrders =
- customers.SelectMany(
- (cust, custIndex) =>
- orders.Where(o => cust.Field<string>("CustomerID") == o.Field<string>("CustomerID"))
- .Select(o => new {CustomerIndex = custIndex + 1, OrderID = o.Field<int>("OrderID")}));
-
- foreach(var c in customerOrders) {
- Console.WriteLine("Customer Index: " + c.CustomerIndex +
- " has an order with OrderID " + c.OrderID);
- }
- }
-
- #endregion
-
- #region "Partioning Operators"
-
- [Category("Partitioning Operators")]
- [Title("Take - Simple")]
- [Description("This sample uses Take to get only the first 3 elements of " +
- "the array.")]
- public void DataSetLinq20() {
-
- var numbers = testDS.Tables["Numbers"].AsEnumerable();
-
- var first3Numbers = numbers.Take(3);
-
- Console.WriteLine("First 3 numbers:");
- foreach (var n in first3Numbers) {
- Console.WriteLine(n.Field<int>("number"));
- }
- }
-
- [Category("Partitioning Operators")]
- [Title("Take - Nested")]
- [Description("This sample uses Take to get the first 3 orders from customers " +
- "in Washington.")]
- public void DataSetLinq21() {
-
- var customers = testDS.Tables["Customers"].AsEnumerable();
- var orders = testDS.Tables["Orders"].AsEnumerable();
-
- var first3WAOrders = (
- from c in customers
- from o in orders
- where c.Field<string>("CustomerID") == o.Field<string>("CustomerID")
- && c.Field<string>("Region") == "WA"
- select new {CustomerID = c.Field<string>("CustomerID"), OrderID = o.Field<int>("OrderID"),
- OrderDate = o.Field<DateTime>("OrderDate")} ).Take(3);
-
- Console.WriteLine("First 3 orders in WA:");
- foreach (var order in first3WAOrders) {
- ObjectDumper.Write(order);
- }
- }
-
- [Category("Partitioning Operators")]
- [Title("Skip - Simple")]
- [Description("This sample uses Skip to get all but the first 4 elements of " +
- "the array.")]
- public void DataSetLinq22() {
-
- var numbers = testDS.Tables["Numbers"].AsEnumerable();
-
- var allButFirst4Numbers = numbers.Skip(4);
-
- Console.WriteLine("All but first 4 numbers:");
- foreach (var n in allButFirst4Numbers) {
- Console.WriteLine(n.Field<int>("number"));
- }
- }
-
- [Category("Partitioning Operators")]
- [Title("Skip - Nested")]
- [Description("This sample uses Skip to get all but the first 2 orders from customers " +
- "in Washington.")]
- public void DataSetLinq23() {
-
- var customers = testDS.Tables["Customers"].AsEnumerable();
- var orders = testDS.Tables["Orders"].AsEnumerable();
-
- var allButFirst2Orders = (
- from c in customers
- from o in orders
- where c.Field<string>("CustomerID") == o.Field<string>("CustomerID")
- && c.Field<string>("Region") == "WA"
- select new {CustomerID = c.Field<string>("CustomerID"), OrderID = o.Field<int>("OrderID"),
- OrderDate = o.Field<DateTime>("OrderDate")} ).Skip(2);
-
- Console.WriteLine("All but first 2 orders in WA:");
- foreach (var order in allButFirst2Orders) {
- ObjectDumper.Write(order);
- }
- }
-
- [Category("Partitioning Operators")]
- [Title("TakeWhile - Simple")]
- [Description("This sample uses TakeWhile to return elements starting from the " +
- "beginning of the array until a number is hit that is not less than 6.")]
- public void DataSetLinq24() {
-
- var numbers = testDS.Tables["Numbers"].AsEnumerable();
-
- var firstNumbersLessThan6 = numbers.TakeWhile(n => n.Field<int>("number") < 6);
-
- Console.WriteLine("First numbers less than 6:");
- foreach (var n in firstNumbersLessThan6) {
- Console.WriteLine(n.Field<int>("number"));
- }
- }
-
- [Category("Partitioning Operators")]
- [Title("TakeWhile - Indexed")]
- [Description("This sample uses TakeWhile to return elements starting from the " +
- "beginning of the array until a number is hit that is less than its position " +
- "in the array.")]
- public void DataSetLinq25() {
-
- var numbers = testDS.Tables["Numbers"].AsEnumerable();
-
- var firstSmallNumbers = numbers.TakeWhile((n, index) => n.Field<int>("number") >= index);
-
- Console.WriteLine("First numbers not less than their position:");
- foreach (var n in firstSmallNumbers) {
- Console.WriteLine(n.Field<int>("number"));
- }
- }
-
- [Category("Partitioning Operators")]
- [Title("SkipWhile - Simple")]
- [Description("This sample uses SkipWhile to get the elements of the array " +
- "starting from the first element divisible by 3.")]
- public void DataSetLinq26() {
-
- var numbers = testDS.Tables["Numbers"].AsEnumerable();
-
- var allButFirst3Numbers = numbers.SkipWhile(n => n.Field<int>("number") % 3 != 0);
-
- Console.WriteLine("All elements starting from first element divisible by 3:");
- foreach (var n in allButFirst3Numbers) {
- Console.WriteLine(n.Field<int>("number"));
- }
- }
-
- [Category("Partitioning Operators")]
- [Title("SkipWhile - Indexed")]
- [Description("This sample uses SkipWhile to get the elements of the array " +
- "starting from the first element less than its position.")]
- public void DataSetLinq27() {
-
- var numbers = testDS.Tables["Numbers"].AsEnumerable();
-
- var laterNumbers = numbers.SkipWhile((n, index) => n.Field<int>("number") >= index);
-
- Console.WriteLine("All elements starting from first element less than its position:");
- foreach (var n in laterNumbers) {
- Console.WriteLine(n.Field<int>("number"));
- }
- }
-
-
- #endregion
-
- #region "Ordering Operators"
-
- [Category("Ordering Operators")]
- [Title("OrderBy - Simple 1")]
- [Description("This sample uses orderby to sort a list of words alphabetically.")]
- public void DataSetLinq28() {
-
- var words = testDS.Tables["Words"].AsEnumerable();
-
- var sortedWords =
- from w in words
- orderby w.Field<string>("word")
- select w;
-
- Console.WriteLine("The sorted list of words:");
- foreach (var w in sortedWords) {
- Console.WriteLine(w.Field<string>("word"));
- }
- }
-
- [Category("Ordering Operators")]
- [Title("OrderBy - Simple 2")]
- [Description("This sample uses orderby to sort a list of words by length.")]
- public void DataSetLinq29() {
-
- var words = testDS.Tables["Words"].AsEnumerable();
-
- var sortedWords =
- from w in words
- orderby w.Field<string>("word").Length
- select w;
-
- Console.WriteLine("The sorted list of words (by length):");
- foreach (var w in sortedWords) {
- Console.WriteLine(w.Field<string>("word"));
- }
-
-
- }
-
- [Category("Ordering Operators")]
- [Title("OrderBy - Simple 3")]
- [Description("This sample uses orderby to sort a list of products by name.")]
- public void DataSetLinq30() {
-
- var products = testDS.Tables["Products"].AsEnumerable();
-
- var sortedProducts =
- from p in products
- orderby p.Field<string>("ProductName")
- select p.Field<string>("ProductName");
-
- ObjectDumper.Write(sortedProducts);
- }
-
- private class CaseInsensitiveComparer : IComparer<string>
- {
- public int Compare(string x, string y)
- {
- return string.Compare(x, y, true);
- }
- }
-
- [Category("Ordering Operators")]
- [Title("OrderBy - Comparer")]
- [Description("This sample uses an OrderBy clause with a custom comparer to " +
- "do a case-insensitive sort of the words in an array.")]
- [LinkedClass("CaseInsensitiveComparer")]
- public void DataSetLinq31() {
-
- var words3 = testDS.Tables["Words3"].AsEnumerable();
-
- var sortedWords = words3.OrderBy(a => a.Field<string>("word"), new CaseInsensitiveComparer());
-
- foreach (var dr in sortedWords)
- {
- Console.WriteLine(dr.Field<string>("word"));
- }
- }
-
- [Category("Ordering Operators")]
- [Title("OrderByDescending - Simple 1")]
- [Description("This sample uses orderby and descending to sort a list of " +
- "doubles from highest to lowest.")]
- public void DataSetLinq32() {
-
- var doubles = testDS.Tables["Doubles"].AsEnumerable();
-
- var sortedDoubles =
- from d in doubles
- orderby d.Field<double>("double") descending
- select d.Field<double>("double");
-
- Console.WriteLine("The doubles from highest to lowest:");
- foreach (var d in sortedDoubles) {
- Console.WriteLine(d);
- }
- }
-
- [Category("Ordering Operators")]
- [Title("OrderByDescending - Simple 2")]
- [Description("This sample uses orderby to sort a list of products by units in stock " +
- "from highest to lowest.")]
- public void DataSetLinq33() {
-
- var products = testDS.Tables["Products"].AsEnumerable();
-
- var sortedProducts =
- from p in products
- orderby p.Field<int>("UnitsInStock") descending
- select p.Field<int>("UnitsInStock") ;
-
- ObjectDumper.Write(sortedProducts);
- }
-
- [Category("Ordering Operators")]
- [Title("OrderByDescending - Comparer")]
- [Description("This sample uses an OrderBy clause with a custom comparer to " +
- "do a case-insensitive descending sort of the words in an array.")]
- [LinkedClass("CaseInsensitiveComparer")]
- public void DataSetLinq34() {
-
- var words3 = testDS.Tables["Words3"].AsEnumerable();
-
- var sortedWords = words3.OrderByDescending(a => a.Field<string>("word"), new CaseInsensitiveComparer());
-
- foreach (var dr in sortedWords)
- {
- Console.WriteLine(dr.Field<string>("word"));
- }
- }
-
- [Category("Ordering Operators")]
- [Title("ThenBy - Simple")]
- [Description("This sample uses a compound orderby to sort a list of digits, " +
- "first by length of their name, and then alphabetically by the name itself.")]
- public void DataSetLinq35() {
-
- var digits = testDS.Tables["Digits"].AsEnumerable();
-
- var sortedDigits =
- from d in digits
- orderby d.Field<string>("digit").Length, d.Field<string>("digit")[0]
- select d.Field<string>("digit");
-
- Console.WriteLine("Sorted digits by Length then first character:");
- foreach (var d in sortedDigits) {
- Console.WriteLine(d);
- }
- }
-
- [Category("Ordering Operators")]
- [Title("ThenBy - Comparer")]
- [Description("This sample uses an OrderBy and a ThenBy clause with a custom comparer to " +
- "sort first by word length and then by a case-insensitive sort of the words in an array.")]
- [LinkedClass("CaseInsensitiveComparer")]
- public void DataSetLinq36() {
-
- var words3 = testDS.Tables["Words3"].AsEnumerable();
-
- var sortedWords =
- words3.OrderBy(a => a.Field<string>("word").Length)
- .ThenBy(a => a.Field<string>("word"), new CaseInsensitiveComparer());
-
- foreach (var dr in sortedWords) {
- Console.WriteLine(dr["word"]);
- }
- }
-
- [Category("Ordering Operators")]
- [Title("ThenByDescending - Simple")]
- [Description("This sample uses a compound orderby to sort a list of products, " +
- "first by category, and then by unit price, from highest to lowest.")]
- public void DataSetLinq37() {
-
- var products = testDS.Tables["Products"].AsEnumerable();
-
- var sortedProducts =
- from p in products
- orderby p.Field<string>("Category"), p.Field<decimal>("UnitPrice") descending
- select p;
-
- foreach (var dr in sortedProducts) {
- Console.WriteLine(dr.Field<string>("ProductName"));
- }
- }
-
- [Category("Ordering Operators")]
- [Title("ThenByDescending - Comparer")]
- [Description("This sample uses an OrderBy and a ThenBy clause with a custom comparer to " +
- "sort first by word length and then by a case-insensitive descending sort " +
- "of the words in an array.")]
- [LinkedClass("CaseInsensitiveComparer")]
- public void DataSetLinq38() {
-
- var words3 = testDS.Tables["Words3"].AsEnumerable();
-
- var sortedWords =
- words3.OrderBy(a => a.Field<string>("word").Length)
- .ThenByDescending(a => a.Field<string>("word"), new CaseInsensitiveComparer());
-
- foreach (var dr in sortedWords){
- Console.WriteLine(dr.Field<string>("word"));
- }
- }
-
- [Category("Ordering Operators")]
- [Title("Reverse")]
- [Description("This sample uses Reverse to create a list of all digits in the array whose " +
- "second letter is 'i' that is reversed from the order in the original array.")]
- public void DataSetLinq39() {
-
- var digits = testDS.Tables["Digits"].AsEnumerable();
-
- var reversedIDigits = (
- from d in digits
- where d.Field<string>("digit")[1] == 'i'
- select d).Reverse();
-
- Console.WriteLine("A backwards list of the digits with a second character of 'i':");
- foreach (var d in reversedIDigits) {
- Console.WriteLine(d.Field<string>("digit"));
- }
- }
-
- [Category("Grouping Operators")]
- [Title("GroupBy - Simple 1")]
- [Description("This sample uses group by to partition a list of numbers by " +
- "their remainder when divided by 5.")]
- public void DataSetLinq40() {
-
- var numbers = testDS.Tables["Numbers"].AsEnumerable();
-
- var numberGroups =
- from n in numbers
- group n by n.Field<int>("number") % 5 into g
- select new {Remainder = g.Key, Numbers = g};
-
- foreach (var g in numberGroups) {
- Console.WriteLine("Numbers with a remainder of {0} when divided by 5:", g.Remainder);
- foreach (var n in g.Numbers) {
- Console.WriteLine(n.Field<int>("number"));
- }
- }
- }
-
- [Category("Grouping Operators")]
- [Title("GroupBy - Simple 2")]
- [Description("This sample uses group by to partition a list of words by " +
- "their first letter.")]
- public void DataSetLinq41() {
-
- var words4 = testDS.Tables["Words4"].AsEnumerable();
-
- var wordGroups =
- from w in words4
- group w by w.Field<string>("word")[0] into g
- select new {FirstLetter = g.Key, Words = g};
-
- foreach (var g in wordGroups) {
- Console.WriteLine("Words that start with the letter '{0}':", g.FirstLetter);
- foreach (var w in g.Words) {
- Console.WriteLine(w.Field<string>("word"));
- }
- }
- }
-
- [Category("Grouping Operators")]
- [Title("GroupBy - Simple 3")]
- [Description("This sample uses group by to partition a list of products by category.")]
- public void DataSetLinq42() {
-
- var products = testDS.Tables["Products"].AsEnumerable();
-
- var productGroups =
- from p in products
- group p by p.Field<string>("Category") into g
- select new {Category = g.Key, Products = g};
-
- foreach (var g in productGroups) {
- Console.WriteLine("Category: {0}", g.Category);
- foreach (var w in g.Products) {
- Console.WriteLine("\t" + w.Field<string>("ProductName"));
- }
- }
- }
-
- [Category("Grouping Operators")]
- [Title("GroupBy - Nested")]
- [Description("This sample uses group by to partition a list of each customer's orders, " +
- "first by year, and then by month.")]
- public void DataSetLinq43() {
-
- var customers = testDS.Tables["Customers"].AsEnumerable();
-
- var customerOrderGroups =
- from c in customers
- select
- new {CompanyName = c.Field<string>("CompanyName"),
- YearGroups =
- from o in c.GetChildRows("CustomersOrders")
- group o by o.Field<DateTime>("OrderDate").Year into yg
- select
- new {Year = yg.Key,
- MonthGroups =
- from o in yg
- group o by o.Field<DateTime>("OrderDate").Month into mg
- select new {Month = mg.Key, Orders = mg}
- }
- };
-
- foreach(var cog in customerOrderGroups) {
- Console.WriteLine("CompanyName= {0}", cog.CompanyName);
- foreach(var yg in cog.YearGroups) {
- Console.WriteLine("\t Year= {0}", yg.Year);
- foreach(var mg in yg.MonthGroups) {
- Console.WriteLine("\t\t Month= {0}", mg.Month);
- foreach(var order in mg.Orders) {
- Console.WriteLine("\t\t\t OrderID= {0} ", order.Field<int>("OrderID"));
- Console.WriteLine("\t\t\t OrderDate= {0} ", order.Field<DateTime>("OrderDate"));
- }
- }
- }
- }
- }
-
- private class AnagramEqualityComparer : IEqualityComparer<string>
- {
- public bool Equals(string x, string y) {
- return getCanonicalString(x) == getCanonicalString(y);
- }
-
- public int GetHashCode(string obj) {
- return getCanonicalString(obj).GetHashCode();
- }
-
- private string getCanonicalString(string word) {
- char[] wordChars = word.ToCharArray();
- Array.Sort<char>(wordChars);
- return new string(wordChars);
- }
- }
-
- [Category("Grouping Operators")]
- [Title("GroupBy - Comparer")]
- [Description("This sample uses GroupBy to partition trimmed elements of an array using " +
- "a custom comparer that matches words that are anagrams of each other.")]
- [LinkedClass("AnagramEqualityComparer")]
- public void DataSetLinq44() {
-
- var anagrams = testDS.Tables["Anagrams"].AsEnumerable();
-
- var orderGroups = anagrams.GroupBy(w => w.Field<string>("anagram").Trim(), new AnagramEqualityComparer());
-
- foreach (var g in orderGroups) {
- Console.WriteLine("Key: {0}", g.Key);
- foreach (var w in g) {
- Console.WriteLine("\t" + w.Field<string>("anagram"));
- }
- }
- }
-
- [Category("Grouping Operators")]
- [Title("GroupBy - Comparer, Mapped")]
- [Description("This sample uses GroupBy to partition trimmed elements of an array using " +
- "a custom comparer that matches words that are anagrams of each other, " +
- "and then converts the results to uppercase.")]
- [LinkedClass("AnagramEqualityComparer")]
- public void DataSetLinq45() {
-
- var anagrams = testDS.Tables["Anagrams"].AsEnumerable();
-
- var orderGroups = anagrams.GroupBy(
- w => w.Field<string>("anagram").Trim(),
- a => a.Field<string>("anagram").ToUpper(),
- new AnagramEqualityComparer()
- );
-
- foreach (var g in orderGroups) {
- Console.WriteLine("Key: {0}", g.Key);
- foreach (var w in g) {
- Console.WriteLine("\t" + w);
- }
- }
- }
-
- #endregion
-
- #region "Set Operators"
-
- [Category("Set Operators")]
- [Title("Distinct - 1")]
- [Description("This sample uses Distinct to remove duplicate elements in a sequence of " +
- "factors of 300.")]
- public void DataSetLinq46() {
-
- var factorsOf300 = testDS.Tables["FactorsOf300"].AsEnumerable();
-
- var uniqueFactors = factorsOf300.Distinct(DataRowComparer.Default);
-
- Console.WriteLine("Prime factors of 300:");
- foreach (var f in uniqueFactors) {
- Console.WriteLine(f.Field<int>("factor"));
- }
- }
-
- [Category("Set Operators")]
- [Title("Distinct - 2")]
- [Description("This sample uses Distinct to find unique employees")]
- public void DataSetLinq47() {
-
- var employees1 = testDS.Tables["employees1"].AsEnumerable();
-
- var employees = employees1.Distinct(DataRowComparer.Default);
-
- foreach (var row in employees) {
- Console.WriteLine("Id: {0} LastName: {1} Level: {2}", row[0], row[1], row[2]);
- }
- }
-
- [Category("Set Operators")]
- [Title("Union - 1")]
- [Description("This sample uses Union to create one sequence that contains the unique values " +
- "from both arrays.")]
- public void DataSetLinq48() {
-
- var numbersA = testDS.Tables["NumbersA"].AsEnumerable();
- var numbersB = testDS.Tables["NumbersB"].AsEnumerable();
-
- var uniqueNumbers = numbersA.Union(numbersB.AsEnumerable(), DataRowComparer.Default);
-
- Console.WriteLine("Unique numbers from both arrays:");
- foreach (var n in uniqueNumbers) {
- Console.WriteLine(n.Field<int>("number"));
- }
-
- }
-
- [Category("Set Operators")]
- [Title("Union - 2")]
- [Description("This sample uses Union to create one sequence based on two DataTables.")]
- public void DataSetLinq49() {
-
- var employees1 = testDS.Tables["employees1"].AsEnumerable();
- var employees2 = testDS.Tables["employees2"].AsEnumerable();
-
- var employees = employees1.Union(employees2, DataRowComparer.Default);
-
- Console.WriteLine("Union of employees tables");
- foreach (var row in employees) {
- Console.WriteLine("Id: {0} LastName: {1} Level: {2}", row[0], row[1], row[2]);
- }
- }
-
- [Category("Set Operators")]
- [Title("Intersect - 1")]
- [Description("This sample uses Intersect to create one sequence that contains the common values " +
- "shared by both arrays.")]
- public void DataSetLinq50() {
-
- var numbersA = testDS.Tables["NumbersA"].AsEnumerable();
- var numbersB = testDS.Tables["NumbersB"].AsEnumerable();
-
- var commonNumbers = numbersA.Intersect(numbersB, DataRowComparer.Default);
-
- Console.WriteLine("Common numbers shared by both arrays:");
- foreach (var n in commonNumbers) {
- Console.WriteLine(n.Field<int>(0));
- }
- }
-
- [Category("Set Operators")]
- [Title("Intersect - 2")]
- [Description("This sample uses Intersect to create one sequence based on two DataTables.")]
- public void DataSetLinq51() {
-
- var employees1 = testDS.Tables["employees1"].AsEnumerable();
- var employees2 = testDS.Tables["employees2"].AsEnumerable();
-
- var employees = employees1.Intersect(employees2, DataRowComparer.Default);
-
- Console.WriteLine("Intersect of employees tables");
- foreach (var row in employees) {
- Console.WriteLine("Id: {0} LastName: {1} Level: {2}", row[0], row[1], row[2]);
- }
- }
-
- [Category("Set Operators")]
- [Title("Except - 1")]
- [Description("This sample uses Except to create a sequence that contains the values from numbersA" +
- "that are not also in numbersB.")]
- public void DataSetLinq52() {
-
- var numbersA = testDS.Tables["NumbersA"].AsEnumerable();
- var numbersB = testDS.Tables["NumbersB"].AsEnumerable();
-
- var aOnlyNumbers = numbersA.Except(numbersB, DataRowComparer.Default);
-
- Console.WriteLine("Numbers in first array but not second array:");
- foreach (var n in aOnlyNumbers) {
- Console.WriteLine(n["number"]);
- }
- }
-
- [Category("Set Operators")]
- [Title("Except - 2")]
- [Description("This sample uses Except to create one sequence based on two DataTables.")]
- public void DataSetLinq53() {
-
- var employees1 = testDS.Tables["employees1"].AsEnumerable();
- var employees2 = testDS.Tables["employees2"].AsEnumerable();
-
- var employees = employees1.Except(employees2, DataRowComparer.Default);
-
- Console.WriteLine("Except of employees tables");
- foreach (var row in employees) {
- Console.WriteLine("Id: {0} LastName: {1} Level: {2}", row[0], row[1], row[2]);
- }
- }
-
-
- #endregion
-
- #region "Conversion Operators"
-
- [Category("Conversion Operators")]
- [Title("ToArray")]
- [Description("This sample uses ToArray to immediately evaluate a sequence into an array.")]
- public void DataSetLinq54() {
-
- var doubles = testDS.Tables["Doubles"].AsEnumerable();
-
- var doublesArray = doubles.ToArray();
-
- var sortedDoubles =
- from d in doublesArray
- orderby d.Field<double>("double") descending
- select d;
-
- Console.WriteLine("Every double from highest to lowest:");
- foreach (var d in sortedDoubles) {
- Console.WriteLine(d.Field<double>("double"));
- }
- }
-
- [Category("Conversion Operators")]
- [Title("ToList")]
- [Description("This sample uses ToList to immediately evaluate a sequence into a List<T>.")]
- public void DataSetLinq55() {
-
- var words = testDS.Tables["Words"].AsEnumerable();
-
- var wordList = words.ToList();
-
- var sortedWords =
- from w in wordList
- orderby w.Field<string>("word")
- select w;
-
- Console.WriteLine("The sorted word list:");
- foreach (var w in sortedWords) {
- Console.WriteLine(w.Field<string>("word").ToLower());
- }
- }
-
- [Category("Conversion Operators")]
- [Title("ToDictionary")]
- [Description("This sample uses ToDictionary to immediately evaluate a sequence and a " +
- "related key expression into a dictionary.")]
- public void DataSetLinq56() {
-
- var scoreRecords = testDS.Tables["ScoreRecords"].AsEnumerable();
-
- var scoreRecordsDict = scoreRecords.ToDictionary(sr => sr.Field<string>("Name"));
- Console.WriteLine("Bob's score: {0}", scoreRecordsDict["Bob"]["Score"]);
- }
-
- [Category("Conversion Operators")]
- [Title("OfType")]
- [Description("This sample uses OfType to return to return IEnumerable<DataRow>")]
- public void DataSetLinq57() {
-
- DataTable numbers = testDS.Tables["Numbers"];
-
- var rows = numbers.Rows.OfType<DataRow>();
- foreach (DataRow d in rows) {
- Console.WriteLine(d.Field<int>("number"));
- }
- }
-
- #endregion
-
- #region "Element Operators"
-
- [Category("Element Operators")]
- [Title("First - Simple")]
- [Description("This sample uses First to return the first matching element " +
- "as a Product, instead of as a sequence containing a Product.")]
- public void DataSetLinq58() {
-
- var products = testDS.Tables["Products"].AsEnumerable();
-
- DataRow product12 = (
- from p in products
- where (int)p["ProductID"] == 12
- select p )
- .First();
-
- Console.WriteLine("ProductId: " + product12.Field<int>("ProductId"));
- Console.WriteLine("ProductName: " + product12.Field<string>("ProductName"));
- }
-
- [Category("Element Operators")]
- [Title("First - Condition")]
- [Description("This sample uses First to find the first element in the array that starts with 'o'.")]
- public void DataSetLinq59() {
-
- var digits = testDS.Tables["Digits"].AsEnumerable();
-
- var startsWithO = digits.First(s => s.Field<string>("digit")[0] == 'o');
-
- Console.WriteLine("A string starting with 'o': {0}", startsWithO.Field<string>("digit"));
- }
-
- [Category("Element Operators")]
- [Title("ElementAt")]
- [Description("This sample uses ElementAt to retrieve the second number greater than 5 " +
- "from an array.")]
- public void DataSetLinq64() {
-
- var numbers = testDS.Tables["Numbers"].AsEnumerable();
-
- var fourthLowNum = (
- from n in numbers
- where n.Field<int>("number") > 5
- select n.Field<int>("number"))
- .ElementAt(3); // 3 because sequences use 0-based indexing
-
- Console.WriteLine("Second number > 5: {0}", fourthLowNum);
- }
-
- [Category("Element Operators")]
- [Title("Def…
Large files files are truncated, but you can click here to view the full file