├── .DS_Store ├── pubspec.yaml ├── pubspec.lock ├── src ├── java │ └── LinqSamples101 │ │ ├── .settings │ │ ├── org.eclipse.m2e.core.prefs │ │ └── org.eclipse.jdt.core.prefs │ │ ├── src │ │ └── main │ │ │ └── java │ │ │ ├── models │ │ │ ├── Orders.java │ │ │ ├── Customers.java │ │ │ ├── Order.java │ │ │ ├── Customer.java │ │ │ └── Product.java │ │ │ ├── linq │ │ │ ├── LinqBase.java │ │ │ ├── LinqQuery.java │ │ │ ├── LinqGeneration.java │ │ │ ├── LinqQuantifiers.java │ │ │ ├── LinqGrouping.java │ │ │ ├── LinqMiscellaneous.java │ │ │ ├── LinqElements.java │ │ │ ├── LinqConversion.java │ │ │ ├── LinqFilters.java │ │ │ ├── LinqPartitions.java │ │ │ ├── LinqSets.java │ │ │ ├── LinqOrdering.java │ │ │ ├── LinqAggregate.java │ │ │ └── LinqProjections.java │ │ │ ├── app │ │ │ └── App.java │ │ │ └── support │ │ │ └── Data.java │ │ ├── .classpath │ │ ├── .project │ │ ├── LinqSamples101.iml │ │ └── pom.xml └── csharp │ ├── linq-sets │ ├── linq-sets.csproj │ └── Program.cs │ ├── linq-shared │ ├── Product.cs │ ├── IEnumerableExtensions.cs │ ├── EmptyClass.cs │ ├── linq-shared.shproj │ ├── linq-shared.projitems │ ├── ObjectDumper.cs │ ├── ProgramBase.cs │ └── TestHelper.cs │ ├── linq-join │ ├── linq-join.csproj │ └── Program.cs │ ├── linq-query │ ├── linq-query.csproj │ └── Program.cs │ ├── linq-element │ ├── linq-element.csproj │ └── Program.cs │ ├── linq-aggregate │ ├── linq-aggregate.csproj │ └── Program.cs │ ├── linq-grouping │ ├── linq-grouping.csproj │ └── Program.cs │ ├── linq-ordering │ ├── linq-ordering.csproj │ └── Program.cs │ ├── linq-conversion │ ├── linq-conversion.csproj │ └── Program.cs │ ├── linq-generation │ ├── linq-generation.csproj │ └── Program.cs │ ├── linq-projections │ ├── linq-projections.csproj │ └── Program.cs │ ├── linq-quantifiers │ ├── linq-quantifiers.csproj │ └── Program.cs │ ├── linq-partitioning │ ├── linq-partitioning.csproj │ └── Program.cs │ ├── linq-restrictions │ ├── linq-restrictions.csproj │ ├── linq-restrictions.sln │ └── Program.cs │ ├── linq-miscellaneous │ ├── linq-miscellaneous.csproj │ └── Program.cs │ └── LinqSamples101.sln └── .gitignore /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rogerwcpt/java-linq-examples/HEAD/.DS_Store -------------------------------------------------------------------------------- /pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: play 2 | description: A sample command-line application 3 | 4 | #dependencies: 5 | # unittest: any -------------------------------------------------------------------------------- /pubspec.lock: -------------------------------------------------------------------------------- 1 | # Generated by pub 2 | # See https://www.dartlang.org/tools/pub/glossary#lockfile 3 | packages: {} 4 | sdks: 5 | dart: any 6 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Package Files # 4 | *.jar 5 | *.war 6 | *.ear 7 | .vscode 8 | bin 9 | obj 10 | .idea 11 | .vs 12 | tools 13 | __pycache__ 14 | .pytest_cache 15 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/src/main/java/models/Orders.java: -------------------------------------------------------------------------------- 1 | package models; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | 5 | import java.util.List; 6 | 7 | public class Orders { 8 | @JsonProperty("order") 9 | public List orderList; 10 | } 11 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/src/main/java/models/Customers.java: -------------------------------------------------------------------------------- 1 | package models; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | 5 | import java.util.List; 6 | 7 | public class Customers { 8 | @JsonProperty("customers") 9 | public List customers; 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /src/csharp/linq-sets/linq-sets.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | Exe 4 | netcoreapp2.1 5 | linq_sets 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/src/main/java/linq/LinqBase.java: -------------------------------------------------------------------------------- 1 | package linq; 2 | 3 | public class LinqBase { 4 | 5 | public static void print(String s) { 6 | System.out.println(s); 7 | } 8 | 9 | public static void print(String format, Object... args) { 10 | System.out.println(String.format(format, args)); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/src/main/java/linq/LinqQuery.java: -------------------------------------------------------------------------------- 1 | package linq; 2 | 3 | public class LinqQuery extends LinqBase { 4 | 5 | public static void Linq99() { 6 | print("TODO"); 7 | } 8 | 9 | public static void Linq100() { 10 | print("TODO"); 11 | } 12 | 13 | public static void Linq101() { 14 | print("TODO"); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/csharp/linq-shared/Product.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace linqshared 4 | { 5 | public class Product 6 | { 7 | public int ProductID { get; set; } 8 | public string ProductName { get; set; } 9 | public string Category { get; set; } 10 | public decimal UnitPrice { get; set; } 11 | public int UnitsInStock { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/csharp/linq-join/linq-join.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp2.1 6 | linq_join 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/csharp/linq-query/linq-query.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp2.1 6 | linq_query 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/csharp/linq-element/linq-element.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp2.1 6 | linq_element 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/csharp/linq-aggregate/linq-aggregate.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp2.1 6 | linq_aggregate 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/csharp/linq-grouping/linq-grouping.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp2.1 6 | linq_grouping 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/csharp/linq-ordering/linq-ordering.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp2.1 6 | linq_ordering 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/csharp/linq-shared/IEnumerableExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace linqshared 5 | { 6 | public static class IEnumerableExtensions 7 | { 8 | public static void ForEach(this IEnumerable items, Action action) 9 | { 10 | foreach(var item in items) 11 | { 12 | action(item); 13 | } 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/csharp/linq-conversion/linq-conversion.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp2.1 6 | linq_conversion 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/csharp/linq-generation/linq-generation.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp2.1 6 | linq_generation 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/csharp/linq-projections/linq-projections.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp2.1 6 | linq_projections 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/csharp/linq-quantifiers/linq-quantifiers.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp2.1 6 | linq_quantifiers 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/csharp/linq-partitioning/linq-partitioning.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp2.1 6 | linq_partitioning 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/csharp/linq-restrictions/linq-restrictions.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp2.1 6 | linq_restrictions 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/csharp/linq-miscellaneous/linq-miscellaneous.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp2.1 6 | linq_miscellaneous 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/src/main/java/models/Order.java: -------------------------------------------------------------------------------- 1 | package models; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | 5 | import java.util.Date; 6 | 7 | public class Order { 8 | 9 | @JsonProperty("id") 10 | public Integer orderId; 11 | @JsonProperty("orderdate") 12 | public Date orderDate; 13 | public Double total; 14 | 15 | @Override 16 | public String toString() { 17 | return "(Order " + 18 | "id=" + orderId + 19 | ", total=" + total + 20 | ')'; 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | LinqSamples101 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=10 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=10 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 11 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 12 | org.eclipse.jdt.core.compiler.release=disabled 13 | org.eclipse.jdt.core.compiler.source=10 14 | -------------------------------------------------------------------------------- /src/csharp/linq-shared/EmptyClass.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | namespace linqshared 3 | { 4 | public class CustomerInfo 5 | { 6 | 7 | } 8 | 9 | public class Order 10 | { 11 | public int OrderID { get; set; } 12 | public DateTime OrderDate { get; set; } 13 | public decimal Total { get; set; } 14 | } 15 | 16 | public class Customer 17 | { 18 | public string CustomerID { get; set; } 19 | public string CompanyName { get; set; } 20 | public string Address { get; set; } 21 | public string City { get; set; } 22 | public string Region { get; set; } 23 | public string PostalCode { get; set; } 24 | public string Country { get; set; } 25 | public string Phone { get; set; } 26 | public string Fax { get; set; } 27 | public Order[] Orders { get; set; } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/csharp/linq-restrictions/linq-restrictions.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "linq-restrictions", "linq-restrictions.csproj", "{AA79D7DA-6B1C-44FF-B14E-E6A15EDD61E1}" 5 | EndProject 6 | Global 7 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 8 | Debug|Any CPU = Debug|Any CPU 9 | Release|Any CPU = Release|Any CPU 10 | EndGlobalSection 11 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 12 | {AA79D7DA-6B1C-44FF-B14E-E6A15EDD61E1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 13 | {AA79D7DA-6B1C-44FF-B14E-E6A15EDD61E1}.Debug|Any CPU.Build.0 = Debug|Any CPU 14 | {AA79D7DA-6B1C-44FF-B14E-E6A15EDD61E1}.Release|Any CPU.ActiveCfg = Release|Any CPU 15 | {AA79D7DA-6B1C-44FF-B14E-E6A15EDD61E1}.Release|Any CPU.Build.0 = Release|Any CPU 16 | EndGlobalSection 17 | EndGlobal 18 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/src/main/java/linq/LinqGeneration.java: -------------------------------------------------------------------------------- 1 | package linq; 2 | 3 | import java.util.Arrays; 4 | import java.util.stream.Collectors; 5 | import java.util.stream.IntStream; 6 | 7 | public class LinqGeneration extends LinqBase { 8 | 9 | public static void Linq65() { 10 | var numbersEvenOdd = IntStream.range(100, 150) 11 | .mapToObj(n -> new Object() { 12 | int Number = n; 13 | String OddEven = (n % 2 == 0 ? "even" : "odd"); 14 | }) 15 | .collect(Collectors.toList()); 16 | 17 | for (var num: numbersEvenOdd) { 18 | print("The number %d is %s", num.Number, num.OddEven); 19 | } 20 | } 21 | 22 | public static void Linq66() { 23 | var numbers = new int[10]; 24 | 25 | Arrays.fill(numbers, 7); 26 | 27 | for (int number : numbers) { 28 | System.out.println(number); 29 | } 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/src/main/java/linq/LinqQuantifiers.java: -------------------------------------------------------------------------------- 1 | package linq; 2 | 3 | import java.util.Arrays; 4 | 5 | public class LinqQuantifiers extends LinqBase { 6 | 7 | public static void Linq67() { 8 | var words = new String []{ "believe", "relief", "receipt", "field" }; 9 | 10 | var iAfterE = Arrays.stream(words) 11 | .anyMatch(w -> w.contains("ei")); 12 | 13 | print("There is a word that contains in the list that contains 'ei': %s", iAfterE); 14 | } 15 | 16 | public static void Linq69() { 17 | print("TODO"); 18 | } 19 | 20 | public static void Linq70() { 21 | var numbers = new int[] { 1, 11, 3, 19, 41, 65, 19 }; 22 | 23 | var onlyOdd = Arrays.stream(numbers) 24 | .allMatch(n -> n % 2 == 1); 25 | 26 | print("The list contains only odd numbers: %s", onlyOdd); 27 | } 28 | 29 | public static void Linq71() { 30 | print("TODO"); 31 | } 32 | 33 | 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/csharp/linq-shared/linq-shared.shproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | {8326DE7B-F4BB-4F86-8B5D-440175C2F0D5} 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/csharp/linq-shared/linq-shared.projitems: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $(MSBuildAllProjects);$(MSBuildThisFileFullPath) 5 | true 6 | {8326DE7B-F4BB-4F86-8B5D-440175C2F0D5} 7 | 8 | 9 | linq-shared 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/src/main/java/models/Customer.java: -------------------------------------------------------------------------------- 1 | package models; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import com.fasterxml.jackson.annotation.JsonProperty; 5 | import com.fasterxml.jackson.annotation.JsonUnwrapped; 6 | 7 | import java.util.*; 8 | 9 | public class Customer { 10 | @JsonProperty("id") 11 | public String customerId; 12 | @JsonProperty("name") 13 | public String companyName; 14 | public String address; 15 | public String city; 16 | public String region; 17 | @JsonProperty("postalcode") 18 | public String postalCode; 19 | public String country; 20 | public String phone; 21 | public String fax; 22 | @JsonIgnore 23 | public List orders; 24 | @JsonProperty("orders") 25 | public Orders ordersList; 26 | 27 | @Override 28 | public String toString() { 29 | return "Customer{" + 30 | "customerId='" + customerId + '\'' + 31 | ", companyName='" + companyName + '\'' + 32 | ", orders='" + orders.size() + '\'' + 33 | '}'; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/LinqSamples101.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/src/main/java/models/Product.java: -------------------------------------------------------------------------------- 1 | package models; 2 | 3 | public class Product { 4 | public Integer productId; 5 | public String productName; 6 | public String category; 7 | public Double unitPrice; 8 | public Integer unitsInStock; 9 | 10 | public Product(Integer productId, String productName, String category, Double unitPrice, Integer unitsInStock) { 11 | this.productId = productId; 12 | this.productName = productName; 13 | this.category = category; 14 | this.unitPrice = unitPrice; 15 | this.unitsInStock = unitsInStock; 16 | } 17 | 18 | public String getProductName() { 19 | return productName; 20 | } 21 | 22 | public int getUnitsInStock() { 23 | return unitsInStock; 24 | } 25 | 26 | public String getCategory() { 27 | return category; 28 | } 29 | 30 | public Double getUnitPrice() { 31 | return unitPrice; 32 | } 33 | 34 | @Override 35 | public String toString() { 36 | return "(Product " + 37 | "id=" + productId + 38 | ", name=" + productName + 39 | ", cat=" + category + 40 | ", price=" + unitPrice + 41 | ", inStock=" + unitsInStock + 42 | ')'; 43 | } 44 | } -------------------------------------------------------------------------------- /src/csharp/linq-generation/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel; 3 | using System.Linq; 4 | using linqshared; 5 | 6 | namespace linq_generation 7 | { 8 | class Program : ProgramBase 9 | { 10 | static void Main(string[] args) 11 | { 12 | Linq65(); 13 | // Linq66(); 14 | } 15 | 16 | [Category("Generation Operators")] 17 | [Description("This sample uses generates a sequence of numbers from 100 to 149 that is used to find which numbers in that range are odd and even.")] 18 | static void Linq65() 19 | { 20 | var numbers = Enumerable.Range(100, 50) 21 | .Select(n => 22 | new 23 | { 24 | Number = n, 25 | OddEven = n % 2 == 1 ? "odd" : "even" 26 | }); 27 | 28 | numbers.ForEach((n) => Console.WriteLine("The number {0} is {1}.", n.Number, n.OddEven)); 29 | } 30 | 31 | [Category("Generation Operators")] 32 | [Description("This sample uses generates a sequence of repeated numbers that contains the number 7 ten times.")] 33 | static void Linq66() 34 | { 35 | var numbers = Enumerable.Repeat(7, 10); 36 | 37 | numbers.ForEach(Console.WriteLine); 38 | } 39 | 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | groupId 8 | LinqSamples101 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 13 | org.apache.maven.plugins 14 | maven-compiler-plugin 15 | 16 | 10 17 | 10 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | com.fasterxml.jackson.core 26 | jackson-core 27 | 2.9.6 28 | 29 | 30 | 31 | com.fasterxml.jackson.core 32 | jackson-annotations 33 | 2.9.6 34 | 35 | 36 | 37 | com.fasterxml.jackson.core 38 | jackson-databind 39 | 2.9.6 40 | 41 | 42 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/src/main/java/linq/LinqGrouping.java: -------------------------------------------------------------------------------- 1 | package linq; 2 | 3 | import support.Data; 4 | 5 | import java.util.Arrays; 6 | import java.util.stream.Collectors; 7 | 8 | public class LinqGrouping extends LinqBase { 9 | 10 | public static void Linq40() { 11 | var numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 12 | 13 | var numberGroups = Arrays.stream(numbers).boxed() 14 | .collect(Collectors.groupingBy(n -> n % 5, Collectors.toList())); 15 | 16 | for (var key:numberGroups.keySet()) { 17 | print("Numbers with a remainder of %d when divided by 5:", key); 18 | numberGroups.get(key).forEach(System.out::println); 19 | } 20 | } 21 | 22 | public static void Linq41() { 23 | var words = new String [] { "blueberry", "chimpanzee", "abacus", "banana", "apple", "cheese" }; 24 | 25 | var wordGroups = Arrays.stream(words) 26 | .collect(Collectors.groupingBy(w -> w.charAt(0), Collectors.toList())); 27 | 28 | for (var key:wordGroups.keySet()) { 29 | print("Words that start with the letter '%s':", key); 30 | wordGroups.get(key).forEach(System.out::println); 31 | } 32 | } 33 | 34 | public static void Linq42() { 35 | var products = Data.getProductList(); 36 | 37 | var productCategories = products.stream() 38 | .collect(Collectors.groupingBy(p -> p.category, Collectors.toList())); 39 | 40 | for (var key:productCategories.keySet()) { 41 | print("Products in the category '%s':" , key); 42 | productCategories.get(key).forEach(System.out::println); 43 | } 44 | } 45 | 46 | public static void Linq43() { 47 | print("TODO"); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/src/main/java/linq/LinqMiscellaneous.java: -------------------------------------------------------------------------------- 1 | package linq; 2 | 3 | import support.Data; 4 | 5 | import java.util.Arrays; 6 | import java.util.stream.Stream; 7 | 8 | public class LinqMiscellaneous extends LinqBase { 9 | 10 | public static void Linq94() { 11 | int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; 12 | int[] numbersB = { 1, 3, 5, 7, 8 }; 13 | 14 | var allNumbers = Stream 15 | .concat( 16 | Arrays.stream(numbersA).boxed(), 17 | Arrays.stream(numbersB).boxed()); 18 | 19 | print("All numbers from both arrays:"); 20 | allNumbers.forEach(System.out::println); 21 | } 22 | 23 | public static void Linq95() { 24 | var products = Data.getProductList(); 25 | var customers = Data.getCustomerList(); 26 | 27 | var customerNames = customers.stream().map(c -> c.companyName); 28 | var productNames = products.stream().map(p -> p.productName); 29 | 30 | 31 | var allNames = Stream.concat(customerNames, productNames); 32 | 33 | print("Customer and product names:"); 34 | allNames.forEach(System.out::println); 35 | } 36 | 37 | public static void Linq96() { 38 | var wordsA = new String[] { "cherry", "apple", "blueberry" }; 39 | var wordsB = new String[] { "cherry", "apple", "blueberry" }; 40 | 41 | var equal = Arrays.equals(wordsA, wordsB); 42 | 43 | print("The sequences match: %s", equal); 44 | } 45 | 46 | public static void Linq97() { 47 | var wordsA = new String[] { "cherry", "apple", "blueberry" }; 48 | var wordsB = new String[] { "apple", "blueberry", "cherry" }; 49 | 50 | var equal = Arrays.equals(wordsA, wordsB); 51 | 52 | print("The sequences match: %s", equal); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/src/main/java/linq/LinqElements.java: -------------------------------------------------------------------------------- 1 | package linq; 2 | 3 | import support.Data; 4 | 5 | import java.util.Arrays; 6 | 7 | public class LinqElements extends LinqBase { 8 | 9 | public static void Linq58() { 10 | var products = Data.getProductList(); 11 | 12 | var produdct12 = products.stream() 13 | .filter(p -> p.productId == 12) 14 | .findFirst(); 15 | 16 | System.out.println(produdct12); 17 | } 18 | 19 | public static void Linq59() { 20 | var strings = new String[]{ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 21 | 22 | var startsWithO = Arrays.stream(strings) 23 | .filter(s -> s.startsWith("o")) 24 | .findFirst(); 25 | 26 | print("A string starting with 'o': %s", startsWithO); 27 | } 28 | 29 | public static void Linq61() { 30 | var numbers = new int[0]; 31 | 32 | var firstNumOrdDefault = Arrays.stream(numbers).boxed() 33 | .findFirst() 34 | .orElse(0); 35 | 36 | System.out.println(firstNumOrdDefault); 37 | } 38 | 39 | public static void Linq62() { 40 | var products = Data.getProductList(); 41 | 42 | var product789 = products.stream() 43 | .filter(p -> p.productId == 789) 44 | .findFirst() 45 | .orElse(null); 46 | 47 | print("Product 789 exists: %s" , product789 != null); 48 | } 49 | 50 | public static void Linq64() { 51 | var numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 52 | 53 | var secondNumberGreaterThan5 = Arrays.stream(numbers).boxed() 54 | .filter(n -> n > 5) 55 | .toArray() 56 | [1]; 57 | 58 | print("Second number > 5: %d" , secondNumberGreaterThan5); 59 | } 60 | 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/src/main/java/linq/LinqConversion.java: -------------------------------------------------------------------------------- 1 | package linq; 2 | 3 | import java.util.*; 4 | import java.util.stream.Collectors; 5 | 6 | public class LinqConversion extends LinqBase { 7 | 8 | public static void Linq54() { 9 | var list = new double[] { 1.7, 2.3, 1.9, 4.1, 2.9 }; 10 | 11 | var sortedDoubles = Arrays.stream(list).boxed() 12 | .sorted(Comparator.reverseOrder()) 13 | .toArray(); 14 | 15 | print("Every other double from highest to lowest:"); 16 | for (int i = 0; i < sortedDoubles.length; i += 2) { 17 | System.out.println(sortedDoubles[i]); 18 | } 19 | } 20 | 21 | public static void Linq55() { 22 | var words = new String[] { "cherry", "apple", "blueberry" }; 23 | 24 | var wordList = Arrays.stream(words) 25 | .sorted() 26 | .collect(Collectors.toList()); 27 | 28 | print("The sorted word list:"); 29 | wordList.forEach(System.out::println); 30 | } 31 | 32 | public static void Linq56() { 33 | 34 | class StudentScore { 35 | public String name; 36 | public int score; 37 | 38 | public StudentScore(String name, int score) { 39 | this.name = name; 40 | this.score = score; 41 | } 42 | } 43 | 44 | var scoreRecords =new ArrayList(); 45 | scoreRecords.add(new StudentScore("Alice", 50)); 46 | scoreRecords.add(new StudentScore("Bob", 40)); 47 | scoreRecords.add(new StudentScore("Cathy", 45)); 48 | 49 | var scoreRecordsMap= scoreRecords.stream() 50 | .collect(Collectors.toMap(s -> s.name, s -> s.score)); 51 | 52 | print("Bob's score: %s", scoreRecordsMap.get("Bob")); 53 | } 54 | 55 | public static void Linq57() { 56 | var numbers = new Object[]{ null, 1.0, "two", 3, "four", 5, "six", 7.0 }; 57 | 58 | var doubles = Arrays.stream(numbers) 59 | .filter(Double.class::isInstance); 60 | 61 | doubles.forEach(System.out::println); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/src/main/java/linq/LinqFilters.java: -------------------------------------------------------------------------------- 1 | package linq; 2 | 3 | import support.Data; 4 | 5 | import java.util.Arrays; 6 | import java.util.stream.IntStream; 7 | 8 | public class LinqFilters extends LinqBase { 9 | 10 | public static void Linq1() { 11 | var numbers = new int[]{5, 4, 1, 3, 9, 8, 6, 7, 2, 0}; 12 | 13 | var lownumbers = Arrays.stream(numbers) 14 | .filter(x -> x < 5); 15 | 16 | print("Numbers < 5:"); 17 | lownumbers.forEach(System.out::println); 18 | } 19 | 20 | public static void Linq2() { 21 | var products = Data.getProductList(); 22 | 23 | var sold_out_products = products.stream() 24 | .filter(p -> p.unitsInStock == 0); 25 | 26 | print("Sold out products:"); 27 | sold_out_products.forEach(p -> print("%s is sold out!", p.productName)); 28 | } 29 | 30 | public static void Linq3() { 31 | var products = Data.getProductList(); 32 | 33 | var sold_out_products = products.stream() 34 | .filter(p -> p.unitsInStock > 0 && p.unitPrice > 3.00); 35 | 36 | print("In-stock products that cost more than 3.00:"); 37 | sold_out_products.forEach(p -> print("%s is in stock and costs more than 3.00.", p.productName)); 38 | } 39 | 40 | public static void Linq4() { 41 | var customers = Data.getCustomerList(); 42 | 43 | var waCustomers = customers.stream() 44 | .filter(c -> "WA".equals(c.region)); 45 | 46 | print("Customers from Washington and their orders:"); 47 | waCustomers.forEach(c -> { 48 | print(String.format("%s : %s", c.customerId, c.companyName)); 49 | c.orders.forEach(o -> print(" Order %s: %s\"", o.orderId, o.orderDate)); 50 | }); 51 | } 52 | 53 | public static void Linq5() { 54 | var digits = new String[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 55 | 56 | var shortDigits = IntStream.range(0, digits.length) 57 | .mapToObj(index -> new Object() { 58 | int Index = index; 59 | String Digit = digits[index]; 60 | }) 61 | .filter(o -> o.Digit.length() < o.Index); 62 | 63 | print("Short digits:"); 64 | shortDigits.forEach(o -> print("The word %s is shorter than its value", o.Digit)); 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/src/main/java/linq/LinqPartitions.java: -------------------------------------------------------------------------------- 1 | package linq; 2 | 3 | import java.util.Arrays; 4 | import java.util.stream.IntStream; 5 | 6 | 7 | public class LinqPartitions extends LinqBase { 8 | 9 | public static void Linq20() { 10 | var numbers = new int[]{5, 4, 1, 3, 9, 8, 6, 7, 2, 0}; 11 | 12 | var first3Numbers = Arrays.stream(numbers) 13 | .limit(3); 14 | 15 | print("First 3 numbers:"); 16 | first3Numbers.forEach(System.out::println); 17 | } 18 | 19 | public static void Linq21() { 20 | print("TODO"); 21 | } 22 | 23 | public static void Linq22() { 24 | print("TODO"); 25 | } 26 | 27 | public static void Linq23() { 28 | print("TODO"); 29 | } 30 | 31 | public static void Linq24() { 32 | var numbers = new int[]{5, 4, 1, 3, 9, 8, 6, 7, 2, 0}; 33 | 34 | var firstNumbersLessThan6 = Arrays.stream(numbers) 35 | .boxed() 36 | .takeWhile(n -> n < 6); 37 | 38 | print("First numbers less than 6:"); 39 | firstNumbersLessThan6.forEach(System.out::println); 40 | } 41 | 42 | public static void Linq25() { 43 | var numbers = new int[]{5, 4, 1, 3, 9, 8, 6, 7, 2, 0}; 44 | 45 | var firstSmallNumbers = IntStream.range(0, numbers.length) 46 | .mapToObj(index -> new Object() { 47 | int Num = numbers[index]; 48 | int Index = index; 49 | }).takeWhile(x -> x.Num >= x.Index); 50 | 51 | print("First numbers not less than their position:"); 52 | firstSmallNumbers.forEach(x -> print("%d", x.Num)); 53 | } 54 | 55 | public static void Linq26() { 56 | var numbers = new int[]{5, 4, 1, 3, 9, 8, 6, 7, 2, 0}; 57 | 58 | var allButFirst3Numbers = Arrays.stream(numbers) 59 | .boxed() 60 | .dropWhile(n -> n % 3 != 0); 61 | 62 | print("All elements starting from first element divisible by 3:"); 63 | allButFirst3Numbers.forEach(System.out::println); 64 | } 65 | 66 | public static void Linq27() { 67 | var numbers = new int[]{5, 4, 1, 3, 9, 8, 6, 7, 2, 0}; 68 | 69 | var firstSmallNumbers = IntStream.range(0, numbers.length) 70 | .mapToObj(index -> new Object() { 71 | int Num = numbers[index]; 72 | int Index = index; 73 | }).dropWhile(x -> x.Num >= x.Index); 74 | 75 | print("First numbers not less than their position:"); 76 | firstSmallNumbers.forEach(x -> print("%d", x.Num)); 77 | } 78 | } 79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /src/csharp/linq-miscellaneous/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.ComponentModel; 4 | using linqshared; 5 | 6 | namespace linq_miscellaneous 7 | { 8 | class Program : ProgramBase 9 | { 10 | static void Main(string[] args) 11 | { 12 | Linq94(); 13 | // Linq95(); 14 | // Linq96(); 15 | // Linq97(); 16 | } 17 | 18 | [Category("Miscellaneous Operators")] 19 | [Description("This sample creates a contatenation of each array's values, one after the other.")] 20 | static void Linq94() 21 | { 22 | int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; 23 | int[] numbersB = { 1, 3, 5, 7, 8 }; 24 | 25 | var allNumbers = numbersA.Concat(numbersB); 26 | 27 | Console.WriteLine("All numbers from both arrays:"); 28 | allNumbers.ForEach(Console.WriteLine); 29 | } 30 | 31 | [ Category("Miscellaneous Operators")] 32 | [Description("This sample creates a contatenation that contains the names of all customers and products, including any duplicates.")] 33 | static void Linq95() 34 | { 35 | var customers = GetCustomerList(); 36 | var products = GetProductList(); 37 | 38 | var customerNames = customers.Select(cust => cust.CompanyName); 39 | var productNames = products.Select(prod => prod.ProductName); 40 | 41 | var allNames = customerNames.Concat(productNames); 42 | 43 | Console.WriteLine("Customer and product names:"); 44 | allNames.ForEach(Console.WriteLine); 45 | } 46 | 47 | [Category("Miscellaneous Operators")] 48 | [Description("This sample checks if two sequences match on all elements in the same order.")] 49 | static void Linq96() 50 | { 51 | var wordsA = new[] { "cherry", "apple", "blueberry" }; 52 | var wordsB = new[] { "cherry", "apple", "blueberry" }; 53 | 54 | var match = wordsA.SequenceEqual(wordsB); 55 | 56 | Console.WriteLine($"The sequences match: {match}"); 57 | } 58 | 59 | [Category("Miscellaneous Operators")] 60 | [Description("This sample checks if two sequences match on all elements in the same order.")] 61 | static void Linq97() 62 | { 63 | var wordsA = new[] { "cherry", "apple", "blueberry" }; 64 | var wordsB = new[] { "apple", "blueberry", "cherry" }; 65 | 66 | var match = wordsA.SequenceEqual(wordsB); 67 | 68 | Console.WriteLine($"The sequences match: {match}"); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/csharp/linq-conversion/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Linq; 5 | using linqshared; 6 | 7 | namespace linq_conversion 8 | { 9 | class Program : ProgramBase 10 | { 11 | static void Main(string[] args) 12 | { 13 | Linq54(); 14 | // Linq55(); 15 | // Linq56(); 16 | // Linq57(); 17 | } 18 | 19 | [Category("Conversion Operators")] 20 | [Description("This sample converts a list to an array.")] 21 | static void Linq54() 22 | { 23 | var list = new List { 1.7, 2.3, 1.9, 4.1, 2.9 }; 24 | 25 | var doublesArray = list 26 | .OrderByDescending(d => d) 27 | .ToArray(); 28 | 29 | Console.WriteLine("Every other double from highest to lowest:"); 30 | for (var d = 0; d < doublesArray.Length; d += 2) 31 | { 32 | Console.WriteLine(doublesArray[d]); 33 | } 34 | } 35 | 36 | 37 | [Category("Conversion Operators")] 38 | [Description("This sample converts an array to a list")] 39 | static void Linq55() 40 | { 41 | var words = new[] { "cherry", "apple", "blueberry" }; 42 | 43 | var wordList = words 44 | .OrderBy(x => x) 45 | .ToList(); 46 | 47 | Console.WriteLine("The sorted word list:"); 48 | wordList.ForEach(Console.WriteLine); 49 | } 50 | 51 | [Category("Conversion Operators")] 52 | [Description("This sample converts an array of records to a dictionary")] 53 | static void Linq56() 54 | { 55 | var scoreRecords = 56 | new[] 57 | { 58 | new {Name = "Alice", Score = 50}, 59 | new {Name = "Bob" , Score = 40}, 60 | new {Name = "Cathy", Score = 45} 61 | }; 62 | 63 | var scoreRecordsDict = scoreRecords.ToDictionary(sr => sr.Name); 64 | 65 | Console.WriteLine("Bob's score: {0}", scoreRecordsDict["Bob"]); 66 | } 67 | 68 | [Category("Conversion Operators")] 69 | [Description("This sample filters all elements that matches the type double.")] 70 | static void Linq57() 71 | { 72 | var numbers = new object[]{ null, 1.0, "two", 3, "four", 5, "six", 7.0 }; 73 | 74 | var doubles = numbers.OfType(); 75 | 76 | Console.WriteLine("Numbers stored as doubles:"); 77 | doubles.ForEach(Console.WriteLine); 78 | } 79 | 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/csharp/linq-quantifiers/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.ComponentModel; 4 | 5 | using linqshared; 6 | 7 | namespace linq_quantifiers 8 | { 9 | class Program : ProgramBase 10 | { 11 | static void Main(string[] args) 12 | { 13 | Linq67(); 14 | // Linq69(); 15 | // Linq70(); 16 | // Linq72(); 17 | } 18 | 19 | [Category("Quantifiers")] 20 | [Description("This sample uses determines if Any of the words in the array contain the substring 'ei'.")] 21 | static void Linq67() 22 | { 23 | var words = new []{ "believe", "relief", "receipt", "field" }; 24 | 25 | var iAfterE = words.Any(w => w.Contains("ei")); 26 | 27 | Console.WriteLine($"There is a word in the list that contains 'ei': {iAfterE}"); 28 | } 29 | 30 | [Category("Quantifiers")] 31 | [Description("This sample determines if Any of the grouped a list of products only for categories that have at least one product that is out of stock.")] 32 | static void Linq69() 33 | { 34 | var products = GetProductList(); 35 | 36 | var productGroups = products 37 | .GroupBy(prod => prod.Category) 38 | .Where(prodGroup => prodGroup.Any(p => p.UnitsInStock == 0)) 39 | .Select(prodGroup => 40 | new 41 | { 42 | Category = prodGroup.Key, 43 | Products = prodGroup 44 | }); 45 | 46 | ObjectDumper.Write(productGroups, 1); 47 | } 48 | 49 | [Category("Quantifiers")] 50 | [Description("This sample determines if All the elements in the array contain only odd numbers.")] 51 | static void Linq70() 52 | { 53 | var numbers = new [] { 1, 11, 3, 19, 41, 65, 19 }; 54 | 55 | var onlyOdd = numbers.All(n => n % 2 == 1); 56 | 57 | Console.WriteLine($"The list contains only odd numbers: {onlyOdd}"); 58 | } 59 | 60 | [Category("Quantifiers")] 61 | [Description("This sample determines if All elements in the grouped a list of products by categories, have all of their products in stock.")] 62 | static void Linq72() 63 | { 64 | var products = GetProductList(); 65 | 66 | var productGroups = products 67 | .GroupBy(prod => prod.Category) 68 | .Where(prodGroup => prodGroup.All(p => p.UnitsInStock > 0)) 69 | .Select(prodGroup => 70 | new 71 | { 72 | Category = prodGroup.Key, 73 | Products = prodGroup 74 | }); 75 | 76 | ObjectDumper.Write(productGroups, 1); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/csharp/linq-element/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.ComponentModel; 4 | using linqshared; 5 | 6 | namespace linq_element 7 | { 8 | class Program : ProgramBase 9 | { 10 | static void Main(string[] args) 11 | { 12 | Linq58(); 13 | // Linq59(); 14 | // Linq61(); 15 | // Linq62(); 16 | // Linq64(); 17 | } 18 | 19 | [Category("Element Operators")] 20 | [Description("This sample returns the first matching element as a Product, instead of as a sequence containing a Product.")] 21 | static void Linq58() 22 | { 23 | var products = GetProductList(); 24 | 25 | var product12 = products.First(p => p.ProductID == 12); 26 | 27 | ObjectDumper.Write(product12); 28 | } 29 | 30 | [Category("Element Operators")] 31 | [Description("This sample finds the first element in the array that starts with 'o'.")] 32 | static void Linq59() 33 | { 34 | var strings = new []{ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 35 | 36 | var startsWithO = strings.First(s => s.StartsWith('o')); 37 | 38 | Console.WriteLine("A string starting with 'o': {0}", startsWithO); 39 | } 40 | 41 | 42 | [Category("Element Operators")] 43 | [Description("This sample returns the first or default if nothing is found, to try to return the first element of the sequence unless there are no elements, in which case the default value for that type is returned.")] 44 | static void Linq61() 45 | { 46 | var numbers = new int[0]; 47 | 48 | var firstNumOrDefault = numbers.FirstOrDefault(); 49 | 50 | Console.WriteLine(firstNumOrDefault); 51 | } 52 | 53 | [Category("Element Operators")] 54 | [Description("This sample returns the first or default if nothing is found, to return the first product whose ProductID is 789 as a single Product object, unless there is no match, in which case null is returned.")] 55 | static void Linq62() 56 | { 57 | var products = GetProductList(); 58 | 59 | var product789 = products.FirstOrDefault(p => p.ProductID == 789); 60 | 61 | Console.WriteLine("Product 789 exists: {0}", product789 != null); 62 | } 63 | 64 | [Category("Element Operators")] 65 | [Description("This sample retrieve the second number greater than 5 from an array.")] 66 | static void Linq64() 67 | { 68 | var numbers = new [] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 69 | 70 | var fourthLowNum = numbers 71 | .Where(num => num > 5) 72 | .ElementAt(1); 73 | 74 | Console.WriteLine("Second number > 5: {0}", fourthLowNum); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/csharp/linq-query/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.ComponentModel; 4 | 5 | using linqshared; 6 | 7 | namespace linq_query 8 | { 9 | class Program : ProgramBase 10 | { 11 | static void Main(string[] args) 12 | { 13 | Linq99(); 14 | // Linq100(); 15 | // Linq101(); 16 | } 17 | 18 | [Category("Query Execution")] 19 | [Description("The following sample shows how query execution is deferred until the query is enumerated at a foreach statement.")] 20 | static void Linq99() 21 | { 22 | // Queries are not executed until you enumerate over them. 23 | var numbers = new[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 24 | 25 | int i = 0; 26 | var simpleQuery = numbers 27 | .Select(x => i++); 28 | 29 | // The local variable 'i' is not incremented until the query is executed in the foreach loop. 30 | Console.WriteLine($"The current value of i is {i}"); //i is still zero 31 | 32 | simpleQuery.ForEach(item => Console.WriteLine($"v = {item}, i = {i}")); // now i is incremented 33 | } 34 | 35 | [Category("Query Execution")] 36 | [Description("The following sample shows how queries can be executed immediately, and their results stored in memory, with methods such as ToList/list.")] 37 | static void Linq100() 38 | { 39 | // Methods like ToList(), Max(), and Count() cause the query to be executed immediately. 40 | var numbers = new[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 41 | 42 | var i = 0; 43 | var immediateQuery = numbers 44 | .Select(x => ++i) 45 | .ToList(); 46 | 47 | Console.WriteLine("The current value of i is {0}", i); //i has been incremented 48 | 49 | immediateQuery.ForEach(item => Console.WriteLine($"v = {item}, i = {i}")); 50 | } 51 | 52 | [Category("Query Execution")] 53 | [Description("The following sample shows how, because of deferred execution, queries can be used again after data changes and will then operate on the new data.")] 54 | static void Linq101() 55 | { 56 | // Deferred execution lets us define a query once and then reuse it later in various ways. 57 | var numbers = new[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 58 | var lowNumbers = numbers 59 | .Where(num => num <= 3); 60 | 61 | Console.WriteLine("First run numbers <= 3:"); 62 | lowNumbers.ForEach(Console.WriteLine); 63 | 64 | // Modify the source data. 65 | for (var i = 0; i < 10; i++) 66 | { 67 | numbers[i] = -numbers[i]; 68 | } 69 | 70 | // During this second run, the same query object, 71 | // lowNumbers, will be iterating over the new state 72 | // of numbers[], producing different results: 73 | Console.WriteLine("Second run numbers <= 3:"); 74 | lowNumbers.ForEach(Console.WriteLine); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/csharp/linq-restrictions/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | 4 | using linqshared; 5 | using System.ComponentModel; 6 | 7 | namespace linq_restrictions 8 | { 9 | class Program: ProgramBase 10 | { 11 | static void Main(string[] args) 12 | { 13 | Linq1(); 14 | // Linq2(); 15 | // Linq3(); 16 | // Linq4(); 17 | // Linq5(); 18 | } 19 | 20 | [Category("Restriction Operators")] 21 | [Description("This sample uses a filter to find all elements of an array with a value less than 5.")] 22 | static void Linq1() 23 | { 24 | var numbers = new [] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 25 | 26 | var lowNums = numbers.Where(n => n < 5); 27 | 28 | Console.WriteLine("Numbers < 5:"); 29 | lowNums.ForEach(Console.WriteLine); 30 | } 31 | 32 | [Category("Restriction Operators")] 33 | [Description("This sample uses a filter to find all products that are out of stock.")] 34 | static void Linq2() 35 | { 36 | var products = GetProductList(); 37 | 38 | var soldOutProducts = products.Where(p => p.UnitsInStock == 0); 39 | 40 | Console.WriteLine("Sold out products:"); 41 | soldOutProducts.ForEach(x => Console.WriteLine($"{x.ProductName} is sold out!")); 42 | } 43 | 44 | [Category("Restriction Operators")] 45 | [Description("This sample uses a filter to find all products that are in stock and cost more than 3.00 per unit.")] 46 | public static void Linq3() 47 | { 48 | var products = GetProductList(); 49 | 50 | var expensiveInStockProducts = products.Where(p => p.UnitsInStock > 0 && p.UnitPrice > 3.00M); 51 | 52 | Console.WriteLine("In-stock products that cost more than 3.00:"); 53 | expensiveInStockProducts.ForEach(product => Console.WriteLine($"{product.ProductName} is in stock and costs more than 3.00.")); 54 | } 55 | 56 | [Category("Restriction Operators")] 57 | [Description("This sample uses a filter to find all customers in Washington and then it uses a foreach loop to iterate over the orders collection that belongs to each customer.")] 58 | static void Linq4() 59 | { 60 | var customers = GetCustomerList(); 61 | 62 | Console.WriteLine("Customers from Washington and their orders:"); 63 | var waCustomers = customers.Where(c => c.Region == "WA"); 64 | 65 | waCustomers.ForEach((customer) => 66 | { 67 | Console.WriteLine($"Customer {customer.CustomerID}: {customer.CompanyName}"); 68 | customer.Orders.ForEach((order) => 69 | { 70 | Console.WriteLine($" Order {order.OrderID}: {order.OrderDate}"); 71 | }); 72 | }); 73 | } 74 | 75 | [Description("This sample demonstrates an indexed filter that returns digits whose name is shorter than their value.")] 76 | static void Linq5() 77 | { 78 | var digits = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 79 | 80 | var shortDigits = digits.Where((digit, index) => digit.Length < index); 81 | 82 | Console.WriteLine("Short digits:"); 83 | shortDigits.ForEach(d => Console.WriteLine($"The word {d} is shorter than its value.")); 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/src/main/java/linq/LinqSets.java: -------------------------------------------------------------------------------- 1 | package linq; 2 | 3 | import support.Data; 4 | 5 | import java.util.Arrays; 6 | import java.util.stream.Stream; 7 | 8 | public class LinqSets extends LinqBase { 9 | 10 | public static void Linq46() { 11 | int[] factorsOf300 = { 2, 2, 3, 5, 5 }; 12 | 13 | var uniqueFactors = Arrays.stream(factorsOf300).boxed() 14 | .distinct(); 15 | 16 | print("Prime factors of 300:"); 17 | uniqueFactors.forEach(System.out::println); 18 | } 19 | 20 | public static void Linq47() { 21 | var products = Data.getProductList(); 22 | 23 | var productCategories = products.stream() 24 | .map(p -> p.category) 25 | .distinct(); 26 | 27 | print("Category names:"); 28 | productCategories.forEach(System.out::println); 29 | } 30 | 31 | public static void Linq48() { 32 | int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; 33 | int[] numbersB = { 1, 3, 5, 7, 8 }; 34 | 35 | var uniqueNumbers = Stream 36 | .concat( 37 | Arrays.stream(numbersA).boxed(), 38 | Arrays.stream(numbersB).boxed()) 39 | .distinct(); 40 | 41 | print("Unique numbers from both arrays:"); 42 | uniqueNumbers.forEach(System.out::println); 43 | } 44 | 45 | public static void Linq49() { 46 | var products = Data.getProductList(); 47 | var customers = Data.getCustomerList(); 48 | 49 | var productChars = products.stream().map(p -> p.productName.charAt(0)); 50 | var customerChars = customers.stream().map(c -> c.companyName.charAt(0)); 51 | 52 | var uniqueFirstChars = Stream 53 | .concat(productChars, customerChars) 54 | .distinct(); 55 | 56 | print("Unique first letters from Product names and Customer names:"); 57 | uniqueFirstChars.forEach(System.out::println); 58 | } 59 | 60 | 61 | public static void Linq50() { 62 | int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; 63 | int[] numbersB = { 1, 3, 5, 7, 8 }; 64 | 65 | var uniqueNumbers = Arrays.stream(numbersA) 66 | .filter(a -> Arrays.stream(numbersB).anyMatch(b -> b == a)); 67 | 68 | print("Common numbers shared by both arrays:"); 69 | uniqueNumbers.forEach(System.out::println); 70 | } 71 | 72 | public static void Linq51() { 73 | var products = Data.getProductList(); 74 | var customers = Data.getCustomerList(); 75 | 76 | var uniqueFirstChars = products.stream() 77 | .map(p -> p.productName.charAt(0)) 78 | .filter(p -> customers.stream().map(c -> c.companyName.charAt(0)).anyMatch(c -> c == p)) 79 | .distinct(); 80 | 81 | print("Common first letters from Product names and Customer names:"); 82 | uniqueFirstChars.forEach(System.out::println); 83 | } 84 | 85 | public static void Linq52() { 86 | int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; 87 | int[] numbersB = { 1, 3, 5, 7, 8 }; 88 | 89 | var uniqueNumbers = Arrays.stream(numbersA) 90 | .filter(a -> Arrays.stream(numbersB).noneMatch(b -> b == a)); 91 | 92 | print("Common numbers shared by both arrays:"); 93 | uniqueNumbers.forEach(System.out::println); 94 | } 95 | 96 | public static void Linq53() { 97 | var products = Data.getProductList(); 98 | var customers = Data.getCustomerList(); 99 | 100 | var uniqueFirstChars = products.stream() 101 | .map(p -> p.productName.charAt(0)) 102 | .filter(p -> customers.stream().map(c -> c.companyName.charAt(0)).noneMatch(c -> c == p)) 103 | .distinct(); 104 | 105 | print("Common first letters from Product names and Customer names:"); 106 | uniqueFirstChars.forEach(System.out::println); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/src/main/java/app/App.java: -------------------------------------------------------------------------------- 1 | package app; 2 | 3 | 4 | public class App { 5 | public static void main(String[] args) throws Exception { 6 | 7 | // Filters 8 | // linq.LinqFilters.Linq1(); 9 | // linq.LinqFilters.Linq2(); 10 | // linq.LinqFilters.Linq3(); 11 | // linq.LinqFilters.Linq4(); 12 | // linq.LinqFilters.Linq5(); 13 | 14 | // Projections 15 | // linq.LinqProjections.Linq6(); 16 | // linq.LinqProjections.Linq7(); 17 | // linq.LinqProjections.Linq8(); 18 | // linq.LinqProjections.Linq9(); 19 | // linq.LinqProjections.Linq10(); 20 | // linq.LinqProjections.Linq11(); 21 | // linq.LinqProjections.Linq12(); 22 | // linq.LinqProjections.Linq13(); 23 | // linq.LinqProjections.Linq14(); 24 | // linq.LinqProjections.Linq15(); 25 | // linq.LinqProjections.Linq16(); 26 | // linq.LinqProjections.Linq17(); 27 | // linq.LinqProjections.Linq18(); 28 | // linq.LinqProjections.Linq19(); 29 | 30 | // Partitions 31 | // linq.LinqPartitions.Linq20(); 32 | // linq.LinqPartitions.Linq21(); 33 | // linq.LinqPartitions.Linq22(); 34 | // linq.LinqPartitions.Linq23(); 35 | // linq.LinqPartitions.Linq24(); 36 | // linq.LinqPartitions.Linq25(); 37 | // linq.LinqPartitions.Linq26(); 38 | // linq.LinqPartitions.Linq27(); 39 | 40 | 41 | // Ordering 42 | // linq.LinqOrdering.Linq28(); 43 | // linq.LinqOrdering.Linq29(); 44 | // linq.LinqOrdering.Linq30(); 45 | // linq.LinqOrdering.Linq31(); 46 | // linq.LinqOrdering.Linq32(); 47 | // linq.LinqOrdering.Linq33(); 48 | // linq.LinqOrdering.Linq34(); 49 | // linq.LinqOrdering.Linq35(); 50 | // linq.LinqOrdering.Linq36(); 51 | // linq.LinqOrdering.Linq37(); 52 | // linq.LinqOrdering.Linq38(); 53 | // linq.LinqOrdering.Linq39(); 54 | 55 | // Grouping 56 | // linq.LinqGrouping.Linq40(); 57 | // linq.LinqGrouping.Linq41(); 58 | // linq.LinqGrouping.Linq42(); 59 | // linq.LinqGrouping.Linq43(); 60 | 61 | // Sets 62 | // linq.LinqSets.Linq46(); 63 | // linq.LinqSets.Linq47(); 64 | // linq.LinqSets.Linq48(); 65 | // linq.LinqSets.Linq49(); 66 | // linq.LinqSets.Linq50(); 67 | // linq.LinqSets.Linq51(); 68 | // linq.LinqSets.Linq52(); 69 | // linq.LinqSets.Linq53(); 70 | 71 | // Conversion 72 | // linq.LinqConversion.Linq54(); 73 | // linq.LinqConversion.Linq55(); 74 | // linq.LinqConversion.Linq56(); 75 | // linq.LinqConversion.Linq57(); 76 | 77 | // Elements 78 | // linq.LinqElements.Linq58(); 79 | // linq.LinqElements.Linq59(); 80 | // linq.LinqElements.Linq61(); 81 | // linq.LinqElements.Linq62(); 82 | // linq.LinqElements.Linq64(); 83 | 84 | // Generation 85 | // linq.LinqGeneration.Linq65(); 86 | // linq.LinqGeneration.Linq66(); 87 | 88 | // Quantifiers 89 | // linq.LinqQuantifiers.Linq67(); 90 | // linq.LinqQuantifiers.Linq69(); 91 | // linq.LinqQuantifiers.Linq70(); 92 | // linq.LinqQuantifiers.Linq71(); 93 | 94 | //Aggregates 95 | // linq.LinqAggregate.Linq73(); 96 | // linq.LinqAggregate.Linq74(); 97 | // linq.LinqAggregate.Linq75(); 98 | // linq.LinqAggregate.Linq77(); 99 | // linq.LinqAggregate.Linq78(); 100 | // linq.LinqAggregate.Linq79(); 101 | // linq.LinqAggregate.Linq80(); 102 | // linq.LinqAggregate.Linq81(); 103 | // linq.LinqAggregate.Linq82(); 104 | // linq.LinqAggregate.Linq83(); 105 | // linq.LinqAggregate.Linq84(); 106 | // linq.LinqAggregate.Linq85(); 107 | // linq.LinqAggregate.Linq86(); 108 | // linq.LinqAggregate.Linq87(); 109 | // linq.LinqAggregate.Linq88(); 110 | // linq.LinqAggregate.Linq89(); 111 | // linq.LinqAggregate.Linq90(); 112 | // linq.LinqAggregate.Linq91(); 113 | // linq.LinqAggregate.Linq92(); 114 | // linq.LinqAggregate.Linq93(); 115 | 116 | //Miscellaneous 117 | // linq.LinqMiscellaneous.Linq94(); 118 | // linq.LinqMiscellaneous.Linq95(); 119 | // linq.LinqMiscellaneous.Linq96(); 120 | // linq.LinqMiscellaneous.Linq97(); 121 | 122 | // Query 123 | // linq.LinqQuery.Linq99(); 124 | // linq.LinqQuery.Linq100(); 125 | // linq.LinqQuery.Linq101(); 126 | } 127 | } -------------------------------------------------------------------------------- /src/csharp/linq-join/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.ComponentModel; 4 | 5 | using linqshared; 6 | 7 | namespace linq_join 8 | { 9 | class Program : ProgramBase 10 | { 11 | static void Main(string[] args) 12 | { 13 | Linq102(); 14 | // Linq103(); 15 | // Linq104(); 16 | // Linq105(); 17 | } 18 | 19 | [Category("Join Operators")] 20 | [Description("This sample shows how to perform a simple inner equijoin of two sequences to produce a flat result set that consists of each element in suppliers that has a matching element in customers.")] 21 | static void Linq102() 22 | { 23 | var categories = new [] {"Beverages","Condiments","Vegetables","Dairy Products","Seafood" }; 24 | 25 | var products = GetProductList(); 26 | 27 | var q = categories 28 | .Join(products, c => c, p => p.Category, (c, p) => 29 | new 30 | { 31 | Category = c, 32 | p.ProductName 33 | }); 34 | 35 | q.ForEach(v => Console.WriteLine($"Category: {v.Category}: Product {v.ProductName}")); 36 | } 37 | 38 | [Category("Join Operators")] 39 | [Description("A group join produces a hierarchical sequence. The following query is an inner join that produces a sequence of objects, each of which has a key and an inner sequence of all matching elements.")] 40 | static void Linq103() 41 | { 42 | var categories = new [] {"Beverages","Condiments","Vegetables","Dairy Products","Seafood" }; 43 | 44 | var products = GetProductList(); 45 | 46 | var q = categories 47 | .GroupJoin(products, c => c, p => p.Category, (c, ps) => 48 | new 49 | { 50 | Category = c, 51 | Products = ps 52 | }); 53 | 54 | q.ForEach((v) => 55 | { 56 | Console.WriteLine(v.Category + ":"); 57 | v.Products.ForEach(p => Console.WriteLine($"\t{p.ProductName}")); 58 | }); 59 | } 60 | 61 | [Category("Join Operators")] 62 | [Description("The group join operator is more general than join, as this slightly more verbose version of the cross join sample shows.")] 63 | static void Linq104() 64 | { 65 | var categories = new [] {"Beverages","Condiments","Vegetables","Dairy Products","Seafood" }; 66 | 67 | var products = GetProductList(); 68 | 69 | var prodByCategory = categories 70 | .GroupJoin(products, cat => cat, prod => prod.Category, 71 | (category, prods) => 72 | new 73 | { 74 | category, 75 | prods 76 | }) 77 | .SelectMany(x => 78 | x.prods, (x, plist) => 79 | new 80 | { 81 | Category = x.category, 82 | plist.ProductName 83 | }); 84 | 85 | prodByCategory.ForEach(item => Console.WriteLine($"{item.ProductName }: {item.Category}")); 86 | } 87 | [Category("Join Operators")] 88 | [Description("A left outer join produces a result set that includes all the left hand side elements at least once, even if they don't match any right hand side elements.")] 89 | static void Linq105() 90 | { 91 | var categories = new [] {"Beverages","Condiments","Vegetables","Dairy Products","Seafood" }; 92 | 93 | var products = GetProductList(); 94 | 95 | var q = categories 96 | .GroupJoin(products, cat => cat, prod => prod.Category, (category, prods) => 97 | new 98 | { 99 | category, 100 | prods 101 | }) 102 | .SelectMany(x => x.prods.DefaultIfEmpty(),(x, p) => 103 | new 104 | { 105 | Category = x.category, 106 | ProductName = p == null ? "(No products)" : p.ProductName 107 | }); 108 | 109 | q.ForEach(item => Console.WriteLine($"{item.ProductName }: {item.Category}")); 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/src/main/java/linq/LinqOrdering.java: -------------------------------------------------------------------------------- 1 | package linq; 2 | 3 | import models.Product; 4 | import support.Data; 5 | 6 | import java.util.*; 7 | import java.util.stream.Collectors; 8 | 9 | public class LinqOrdering extends LinqBase { 10 | 11 | public static void Linq28() { 12 | var words = new String[] { "cherry", "apple", "blueberry" }; 13 | 14 | var sortedWords = Arrays.stream(words) 15 | .sorted(); 16 | 17 | print("The sorted list of words:"); 18 | sortedWords.forEach(System.out::println); 19 | } 20 | 21 | public static void Linq29() { 22 | var words = new String[] { "cherry", "apple", "blueberry" }; 23 | 24 | var sortedWords = Arrays.stream(words) 25 | .sorted(Comparator.comparing(s -> s.length())); 26 | 27 | print("The sorted list of words:"); 28 | sortedWords.forEach(System.out::println); 29 | } 30 | 31 | public static void Linq30() { 32 | var products = Data.getProductList(); 33 | 34 | var sortedProducts = products.stream() 35 | .sorted(Comparator.comparing(p -> p.productName)); 36 | 37 | sortedProducts.forEach(System.out::println); 38 | } 39 | 40 | public static void Linq31() { 41 | var words = new String[] { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" }; 42 | 43 | var sortedWords = Arrays.stream(words). 44 | sorted(Comparator.comparing(s -> s, String.CASE_INSENSITIVE_ORDER)); 45 | 46 | sortedWords.forEach(System.out::println); 47 | } 48 | 49 | public static void Linq32() { 50 | var doubles = new Double[]{ 1.7, 2.3, 1.9, 4.1, 2.9 }; 51 | 52 | var sortedDoubles = Arrays.stream(doubles) 53 | .sorted(Comparator.reverseOrder()); 54 | 55 | print("The doubles from highest to lowest:"); 56 | sortedDoubles.forEach((System.out::println)); 57 | } 58 | 59 | public static void Linq33() { 60 | var products = Data.getProductList(); 61 | 62 | var reverseSortedProducts = products.stream() 63 | .sorted(Comparator.comparing(p -> p.unitsInStock, Comparator.reverseOrder())); 64 | 65 | reverseSortedProducts.forEach(System.out::println); 66 | } 67 | 68 | public static void Linq34() { 69 | var words = new String[] { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" }; 70 | 71 | var sortedWords = Arrays.stream(words). 72 | sorted(Comparator.comparing(String::toString, String.CASE_INSENSITIVE_ORDER).reversed()); 73 | 74 | sortedWords.forEach(System.out::println); 75 | } 76 | 77 | public static void Linq35() { 78 | var digits = new String[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 79 | 80 | var sortedDigits = Arrays.stream(digits) 81 | .sorted( 82 | Comparator 83 | .comparing(String::length) 84 | .thenComparing(s -> s) 85 | ); 86 | 87 | print("Sorted digits:"); 88 | sortedDigits.forEach(System.out::println); 89 | } 90 | 91 | public static void Linq36() { 92 | var words = new String[] { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" }; 93 | 94 | var sortedWords = Arrays.stream(words) 95 | .sorted(Comparator 96 | .comparing(String::length) 97 | .thenComparing(s -> s, String.CASE_INSENSITIVE_ORDER)); 98 | 99 | sortedWords.forEach(System.out::println); 100 | } 101 | 102 | public static void Linq37() { 103 | var products = Data.getProductList(); 104 | 105 | var sortedProducts = products.stream() 106 | .sorted(Comparator 107 | .comparing(Product::getCategory) 108 | .thenComparing(Product::getUnitPrice, Comparator.reverseOrder())); 109 | 110 | sortedProducts.forEach(System.out::println); 111 | } 112 | 113 | public static void Linq38() { 114 | var words = new String[] { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" }; 115 | 116 | var sortedWords = Arrays.stream(words) 117 | .sorted(Comparator 118 | .comparing(String::length) 119 | .thenComparing(s -> s, String.CASE_INSENSITIVE_ORDER.reversed())); 120 | 121 | sortedWords.forEach(System.out::println); 122 | } 123 | 124 | public static void Linq39() { 125 | var digits = new String [] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 126 | 127 | var reversedIDigits = Arrays.stream(digits) 128 | .filter(s -> s.charAt(1) == 'i') 129 | .collect(Collectors.toCollection(LinkedList::new)) 130 | .descendingIterator(); 131 | 132 | print("A backwards list of the digits with a second character of 'i':"); 133 | reversedIDigits.forEachRemaining(System.out::println); 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /src/csharp/linq-shared/ObjectDumper.cs: -------------------------------------------------------------------------------- 1 | // Copyright © Microsoft Corporation. All Rights Reserved. 2 | // This code released under the terms of the 3 | // Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.) 4 | // 5 | //Copyright (C) Microsoft Corporation. All rights reserved. 6 | 7 | using System; 8 | using System.IO; 9 | using System.Collections; 10 | using System.Collections.Generic; 11 | using System.Reflection; 12 | 13 | public class ObjectDumper { 14 | public static void Write(object o) { 15 | Write(o, 0); 16 | } 17 | 18 | public static void Write(object o, int depth) { 19 | ObjectDumper dumper = new ObjectDumper(depth); 20 | dumper.WriteObject(null, o); 21 | } 22 | 23 | TextWriter writer; 24 | int pos; 25 | int level; 26 | int depth; 27 | 28 | private ObjectDumper(int depth) { 29 | this.writer = Console.Out; 30 | this.depth = depth; 31 | } 32 | 33 | private void Write(string s) { 34 | if (s != null) { 35 | writer.Write(s); 36 | pos += s.Length; 37 | } 38 | } 39 | 40 | private void WriteIndent() { 41 | for (int i = 0; i < level; i++) writer.Write(" "); 42 | } 43 | 44 | private void WriteLine() { 45 | writer.WriteLine(); 46 | pos = 0; 47 | } 48 | 49 | private void WriteTab() { 50 | Write(" "); 51 | while (pos % 8 != 0) Write(" "); 52 | } 53 | 54 | private void WriteObject(string prefix, object o) { 55 | if (o == null || o is ValueType || o is string) { 56 | WriteIndent(); 57 | Write(prefix); 58 | WriteValue(o); 59 | WriteLine(); 60 | } 61 | else if (o is IEnumerable) { 62 | foreach (object element in (IEnumerable)o) { 63 | if (element is IEnumerable && !(element is string)) { 64 | WriteIndent(); 65 | Write(prefix); 66 | Write("..."); 67 | WriteLine(); 68 | if (level < depth) { 69 | level++; 70 | WriteObject(prefix, element); 71 | level--; 72 | } 73 | } 74 | else { 75 | WriteObject(prefix, element); 76 | } 77 | } 78 | } 79 | else { 80 | MemberInfo[] members = o.GetType().GetMembers(BindingFlags.Public | BindingFlags.Instance); 81 | WriteIndent(); 82 | Write(prefix); 83 | bool propWritten = false; 84 | foreach (MemberInfo m in members) { 85 | FieldInfo f = m as FieldInfo; 86 | PropertyInfo p = m as PropertyInfo; 87 | if (f != null || p != null) { 88 | if (propWritten) { 89 | WriteTab(); 90 | } 91 | else { 92 | propWritten = true; 93 | } 94 | Write(m.Name); 95 | Write("="); 96 | Type t = f != null ? f.FieldType : p.PropertyType; 97 | if (t.IsValueType || t == typeof(string)) { 98 | WriteValue(f != null ? f.GetValue(o) : p.GetValue(o, null)); 99 | } 100 | else { 101 | if (typeof(IEnumerable).IsAssignableFrom(t)) { 102 | Write("..."); 103 | } 104 | else { 105 | Write("{ }"); 106 | } 107 | } 108 | } 109 | } 110 | if (propWritten) WriteLine(); 111 | if (level < depth) { 112 | foreach (MemberInfo m in members) { 113 | FieldInfo f = m as FieldInfo; 114 | PropertyInfo p = m as PropertyInfo; 115 | if (f != null || p != null) { 116 | Type t = f != null ? f.FieldType : p.PropertyType; 117 | if (!(t.IsValueType || t == typeof(string))) { 118 | object value = f != null ? f.GetValue(o) : p.GetValue(o, null); 119 | if (value != null) { 120 | level++; 121 | WriteObject(m.Name + ": ", value); 122 | level--; 123 | } 124 | } 125 | } 126 | } 127 | } 128 | } 129 | } 130 | 131 | private void WriteValue(object o) { 132 | if (o == null) { 133 | Write("null"); 134 | } 135 | else if (o is DateTime) { 136 | Write(((DateTime)o).ToShortDateString()); 137 | } 138 | else if (o is ValueType || o is string) { 139 | Write(o.ToString()); 140 | } 141 | else if (o is IEnumerable) { 142 | Write("..."); 143 | } 144 | else { 145 | Write("{ }"); 146 | } 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /src/csharp/linq-sets/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel; 3 | using System.Linq; 4 | using linqshared; 5 | 6 | namespace linq_sets 7 | { 8 | class Program: ProgramBase 9 | { 10 | static void Main(string[] args) 11 | { 12 | Linq46(); 13 | // Linq47(); 14 | // Linq48(); 15 | // Linq49(); 16 | // Linq50(); 17 | // Linq51(); 18 | // Linq52(); 19 | // Linq53(); 20 | } 21 | 22 | 23 | [Category("Set Operators")] 24 | [Description("This sample removes all duplicate elements in a sequence of factors of 300.")] 25 | static void Linq46() 26 | { 27 | int[] factorsOf300 = { 2, 2, 3, 5, 5 }; 28 | 29 | var uniqueFactors = factorsOf300.Distinct(); 30 | 31 | Console.WriteLine("Prime factors of 300:"); 32 | uniqueFactors.ForEach(Console.WriteLine); 33 | } 34 | 35 | [Category("Set Operators")] 36 | [Description("This sample gets distint Category names from all the products.")] 37 | static void Linq47() 38 | { 39 | var products = GetProductList(); 40 | 41 | var categoryNames = products 42 | .Select(p => p.Category) 43 | .Distinct(); 44 | 45 | Console.WriteLine("Category names:"); 46 | categoryNames.ForEach(Console.WriteLine); 47 | } 48 | 49 | [Category("Set Operators")] 50 | [Description("This sample creates a Union of sequences that contains unique values from both arrays.")] 51 | static void Linq48() 52 | { 53 | int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; 54 | int[] numbersB = { 1, 3, 5, 7, 8 }; 55 | 56 | var uniqueNumbers = numbersA.Union(numbersB); 57 | 58 | Console.WriteLine("Unique numbers from both arrays:"); 59 | uniqueNumbers.ForEach(Console.WriteLine); 60 | } 61 | 62 | [Category("Set Operators")] 63 | [Description("This sample creates a Union of sequences that contains the distinct first letter from both product and customer names")] 64 | static void Linq49() 65 | { 66 | var products = GetProductList(); 67 | var customers = GetCustomerList(); 68 | 69 | var productFirstChars = products.Select(p => p.ProductName[0]); 70 | var customerFirstChars = customers.Select(c => c.CompanyName[0]); 71 | 72 | var uniqueFirstChars = productFirstChars.Union(customerFirstChars); 73 | 74 | Console.WriteLine("Unique first letters from Product names and Customer names:"); 75 | uniqueFirstChars.ForEach(Console.WriteLine); 76 | } 77 | 78 | [Category("Set Operators")] 79 | [Description("This sample creates Intersection that contains the common values shared by both arrays.")] 80 | static void Linq50() 81 | { 82 | int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; 83 | int[] numbersB = { 1, 3, 5, 7, 8 }; 84 | 85 | var commonNumbers = numbersA.Intersect(numbersB); 86 | 87 | Console.WriteLine("Common numbers shared by both arrays:"); 88 | commonNumbers.ForEach(Console.WriteLine); 89 | } 90 | 91 | [Category("Set Operators")] 92 | [Description("This sample creates Intersection that contains contains the common first letter from both product and customer names.")] 93 | static void Linq51() 94 | { 95 | var products = GetProductList(); 96 | var customers = GetCustomerList(); 97 | 98 | var productFirstChars = products.Select(p => p.ProductName[0]); 99 | var customerFirstChars = customers.Select(c => c.CompanyName[0]); 100 | 101 | var commonFirstChars = productFirstChars.Intersect(customerFirstChars); 102 | 103 | Console.WriteLine("Common first letters from Product names and Customer names:"); 104 | commonFirstChars.ForEach(Console.WriteLine); 105 | } 106 | 107 | 108 | [Category("Set Operators")] 109 | [Description("This sample creates a sequence that excludes the values from the second sequence.")] 110 | static void Linq52() 111 | { 112 | int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; 113 | int[] numbersB = { 1, 3, 5, 7, 8 }; 114 | 115 | var aOnlyNumbers = numbersA.Except(numbersB); 116 | 117 | Console.WriteLine("Numbers in first array but not second array:"); 118 | aOnlyNumbers.ForEach(Console.WriteLine); 119 | } 120 | 121 | [Category("Set Operators")] 122 | [Description("This sample creates a sequence that the first letters of product names that but excludes letters of customer names first letter.")] 123 | static void Linq53() 124 | { 125 | var products = GetProductList(); 126 | var customers = GetCustomerList(); 127 | 128 | var productFirstChars = products.Select(p => p.ProductName[0]); 129 | var customerFirstChars = customers.Select(c => c.CompanyName[0]); 130 | 131 | var productOnlyFirstChars = productFirstChars.Except(customerFirstChars); 132 | 133 | Console.WriteLine("First letters from Product names, but not from Customer names:"); 134 | productOnlyFirstChars.ForEach(Console.WriteLine); 135 | } 136 | 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /src/csharp/linq-partitioning/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel; 3 | using System.Linq; 4 | using linqshared; 5 | 6 | namespace linq_partitioning 7 | { 8 | class Program: ProgramBase 9 | { 10 | static void Main(string[] args) 11 | { 12 | Linq20(); 13 | // Linq21(); 14 | // Linq22(); 15 | // Linq23(); 16 | // Linq24(); 17 | // Linq25(); 18 | // Linq26(); 19 | // Linq27(); 20 | } 21 | 22 | [Category("Partitioning Operators")] 23 | [Description("This sample uses a partition/slice to get only the first 3 elements of the array.")] 24 | static void Linq20() 25 | { 26 | var numbers = new [] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 27 | 28 | var first3Numbers = numbers.Take(3); 29 | 30 | Console.WriteLine("First 3 numbers:"); 31 | first3Numbers.ForEach(Console.WriteLine); 32 | } 33 | 34 | [Category("Partitioning Operators")] 35 | [Description("This sample uses a partition/slice to get the first 3 orders from customers in Washington.")] 36 | static void Linq21() 37 | { 38 | var customers = GetCustomerList(); 39 | 40 | var first3WAOrders = customers 41 | .Where(c => c.Region == "WA") 42 | .SelectMany(customer => customer.Orders, (customer, order) => new { customer, order }) 43 | .Select(x => 44 | new 45 | { 46 | x.customer.CustomerID, 47 | x.order.OrderID, 48 | x.order.OrderDate 49 | }) 50 | .Take(3); 51 | 52 | Console.WriteLine("First 3 orders in WA:"); 53 | first3WAOrders.ForEach(ObjectDumper.Write); 54 | } 55 | 56 | [Category("Partitioning Operators")] 57 | [Description("This sample uses a partition to get all but the first four elements of the array.")] 58 | static void Linq22() 59 | { 60 | var numbers = new []{ 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 61 | 62 | var allButFirst4Numbers = numbers.Skip(4); 63 | 64 | Console.WriteLine("All but first 4 numbers:"); 65 | allButFirst4Numbers.ForEach(Console.WriteLine); 66 | } 67 | 68 | [Category("Partitioning Operators")] 69 | [Description("This sample uses Take to get all but the first 2 orders from customers in Washington.")] 70 | static void Linq23() 71 | { 72 | var customers = GetCustomerList(); 73 | 74 | var waOrders = customers 75 | .Where(c => c.Region == "WA") 76 | .SelectMany(customer => customer.Orders, (customer, order) => new { customer, order }) 77 | .Select(x => 78 | new 79 | { 80 | x.customer.CustomerID, 81 | x.order.OrderID, 82 | x.order.OrderDate 83 | }); 84 | 85 | var allButFirst2Orders = waOrders.Skip(2); 86 | 87 | Console.WriteLine("All but first 2 orders in WA:"); 88 | ObjectDumper.Write(allButFirst2Orders); 89 | } 90 | 91 | [Category("Partitioning Operators")] 92 | [Description("This sample uses a partition to return elements starting from the beginning of the array until a number is read whose value is not less than 6.")] 93 | static void Linq24() 94 | { 95 | var numbers = new[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 96 | 97 | var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 6); 98 | 99 | Console.WriteLine("First numbers less than 6:"); 100 | firstNumbersLessThan6.ForEach(Console.WriteLine); 101 | } 102 | 103 | [Category("Partitioning Operators")] 104 | [Description("This sample uses a partition to return elements starting from the beginning of the array until a number is hit that is less than its position in the array.")] 105 | static void Linq25() 106 | { 107 | var numbers = new [] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 108 | 109 | var firstSmallNumbers = numbers.TakeWhile((n, index) => n >= index); 110 | 111 | Console.WriteLine("First numbers not less than their position:"); 112 | firstSmallNumbers.ForEach(Console.WriteLine); 113 | } 114 | 115 | [Category("Partitioning Operators")] 116 | [Description("This sample uses a partition to get the elements of the array starting from the first element divisible by 3.")] 117 | static void Linq26() 118 | { 119 | var numbers = new [] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 120 | 121 | var allButFirst3Numbers = numbers.SkipWhile(n => n % 3 != 0); 122 | 123 | Console.WriteLine("All elements starting from first element divisible by 3:"); 124 | allButFirst3Numbers.ForEach(Console.WriteLine); 125 | } 126 | 127 | [Category("Partitioning Operators")] 128 | [Description("This sample uses a partition to get the elements of the array starting from the first element less than its position.")] 129 | static void Linq27() 130 | { 131 | var numbers = new [] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 132 | 133 | var laterNumbers = numbers.SkipWhile((n, index) => n >= index); 134 | 135 | Console.WriteLine("All elements starting from first element less than its position:"); 136 | laterNumbers.ForEach(Console.WriteLine); 137 | } 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /src/csharp/linq-grouping/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Linq; 5 | using linqshared; 6 | 7 | namespace linq_grouping 8 | { 9 | class Program: ProgramBase 10 | { 11 | static void Main(string[] args) 12 | { 13 | Linq40(); 14 | // Linq41(); 15 | // Linq42(); 16 | // Linq43(); 17 | // Linq44(); 18 | // Linq45(); 19 | } 20 | 21 | private class AnagramEqualityComparer : IEqualityComparer 22 | { 23 | public bool Equals(string x, string y) 24 | { 25 | return GetCanonicalString(x) == GetCanonicalString(y); 26 | } 27 | 28 | public int GetHashCode(string obj) 29 | { 30 | return GetCanonicalString(obj).GetHashCode(); 31 | } 32 | 33 | private string GetCanonicalString(string word) 34 | { 35 | var wordChars = word.ToCharArray(); 36 | Array.Sort(wordChars); 37 | return new string(wordChars); 38 | } 39 | } 40 | 41 | [Category("Grouping Operators")] 42 | [Description("This sample uses grouping to partition a list of numbers by their remainder when divided by 5.")] 43 | static void Linq40() 44 | { 45 | var numbers = new[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 46 | 47 | var numberGroups = numbers 48 | .GroupBy(n => n % 5) 49 | .Select(x => 50 | new 51 | { 52 | Remainder = x.Key, 53 | Numbers = x 54 | }); 55 | 56 | numberGroups.ForEach((g) => 57 | { 58 | Console.WriteLine("Numbers with a remainder of {0} when divided by 5:", g.Remainder); 59 | g.Numbers.ForEach(Console.WriteLine); 60 | }); 61 | } 62 | 63 | [Category("Grouping Operators")] 64 | [Description("This sample uses grouping to partition a list of words by their first letter.")] 65 | static void Linq41() 66 | { 67 | var words = new [] { "blueberry", "chimpanzee", "abacus", "banana", "apple", "cheese" }; 68 | 69 | var wordGroups = words 70 | .GroupBy(w => w[0]) 71 | .Select(g => 72 | new 73 | { 74 | FirstLetter = g.Key, 75 | Words = g 76 | }); 77 | 78 | wordGroups.ForEach((g) => 79 | { 80 | Console.WriteLine($"Words that start with the letter '{g.FirstLetter}':"); 81 | g.Words.ForEach(Console.WriteLine); 82 | }); 83 | } 84 | 85 | [Category("Grouping Operators")] 86 | [Description("This sample uses grouping to partition a list of products by category.")] 87 | static void Linq42() 88 | { 89 | var products = GetProductList(); 90 | 91 | var orderGroups = products 92 | .GroupBy(p => p.Category) 93 | .Select(g => 94 | new 95 | { 96 | Category = g.Key, 97 | Products = g 98 | }); 99 | 100 | ObjectDumper.Write(orderGroups, 1); 101 | } 102 | 103 | [Category("Grouping Operators")] 104 | [Description("This sample uses nested grouping to partition a list of each customer's orders, first by year, and then by month.")] 105 | static void Linq43() 106 | { 107 | var customers = GetCustomerList(); 108 | 109 | var customerOrderGroups = customers 110 | .Select(c => new 111 | { 112 | c.CompanyName, 113 | YearGroups = 114 | ( 115 | c.Orders 116 | .GroupBy(y => y.OrderDate.Year) 117 | .Select(YearGroup => new 118 | { 119 | Year = YearGroup.Key, 120 | MonthGroups = 121 | ( 122 | YearGroup 123 | .GroupBy(m => m.OrderDate.Month) 124 | .Select(MonthGroup => new 125 | { 126 | Month = MonthGroup.Key, Orders = MonthGroup 127 | }) 128 | 129 | ) 130 | }) 131 | ) 132 | }); 133 | 134 | ObjectDumper.Write(customerOrderGroups, 3); 135 | } 136 | 137 | [Category("Grouping Operators")] 138 | [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.")] 139 | static void Linq44() 140 | { 141 | var anagrams = new [] { "from ", " salt", " earn ", " last ", " near ", " form " }; 142 | var orderGroups = anagrams 143 | .GroupBy(w => w.Trim(), new AnagramEqualityComparer()); 144 | 145 | ObjectDumper.Write(orderGroups, 1); 146 | } 147 | 148 | [Category("Grouping Operators")] 149 | [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.")] 150 | static void Linq45() 151 | { 152 | var anagrams = new [] { "from ", " salt", " earn ", " last ", " near ", " form " }; 153 | 154 | var orderGroups = anagrams.GroupBy( 155 | w => w.Trim(), 156 | a => a.ToUpper(), 157 | new AnagramEqualityComparer() 158 | ); 159 | 160 | ObjectDumper.Write(orderGroups, 1); 161 | } 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/src/main/java/linq/LinqAggregate.java: -------------------------------------------------------------------------------- 1 | package linq; 2 | 3 | import support.Data; 4 | 5 | import java.util.Arrays; 6 | import java.util.Comparator; 7 | import java.util.stream.Collectors; 8 | 9 | public class LinqAggregate extends LinqBase { 10 | 11 | public static void Linq73() { 12 | var primeFactorsOf300 = new int [] { 2, 2, 3, 5, 5 }; 13 | 14 | var uniqueFactors = Arrays.stream(primeFactorsOf300).distinct().count(); 15 | 16 | print("There are %d unique factors of 300.", uniqueFactors); 17 | } 18 | 19 | public static void Linq74() { 20 | var numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 21 | 22 | var oddNumbers = Arrays.stream(numbers) 23 | .filter(n -> n % 2 == 1) 24 | .count(); 25 | 26 | print("There are %d odd numbers in the list.", oddNumbers); 27 | } 28 | 29 | public static void Linq75() { 30 | var customers = Data.getCustomerList(); 31 | 32 | 33 | var orderCounts = customers.stream() 34 | .map(c -> new Object() { 35 | String customerId = c.customerId; 36 | int orderCount = c.orders != null ? c.orders.size() : 0; 37 | }) 38 | .collect(Collectors.toList()); 39 | 40 | for (var o : orderCounts) { 41 | print("{CustomerId: %s, OrderCount: %d}", o.customerId, o.orderCount); 42 | } 43 | } 44 | 45 | public static void Linq77() { 46 | var products = Data.getProductList(); 47 | 48 | var categoryCounts = products.stream() 49 | .collect(Collectors.groupingBy(p -> p.category, Collectors.counting())); 50 | 51 | System.out.println((categoryCounts)); 52 | } 53 | 54 | public static void Linq78() { 55 | var numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 56 | 57 | var numSum = Arrays.stream(numbers).sum(); 58 | 59 | print("The sum of the numbers is %d." , numSum); 60 | } 61 | 62 | public static void Linq79() { 63 | var words = new String[] { "cherry", "apple", "blueberry" }; 64 | 65 | var totalChars = Arrays.stream(words) 66 | .mapToInt(w -> w.length()) 67 | .sum(); 68 | 69 | print("There are a total of %d characters in these words.", totalChars); 70 | } 71 | 72 | public static void Linq80() { 73 | var products = Data.getProductList(); 74 | 75 | var categoryStockCounts = products.stream() 76 | .collect(Collectors.groupingBy(p -> p.category, 77 | Collectors.summingInt(p -> p.unitsInStock))); 78 | 79 | System.out.println((categoryStockCounts)); 80 | } 81 | 82 | public static void Linq81() { 83 | var numbers = new int[]{ 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 84 | 85 | var minNum = Arrays.stream(numbers).min().getAsInt(); 86 | 87 | print("The minimum number is %d", minNum); 88 | } 89 | 90 | public static void Linq82() { 91 | var words = new String[] { "cherry", "apple", "blueberry" }; 92 | 93 | var shortestWord = Arrays.stream(words) 94 | .mapToInt(w -> w.length()) 95 | .min() 96 | .getAsInt(); 97 | 98 | print("The shortest word is %d characters long.", shortestWord); 99 | } 100 | 101 | public static void Linq83() { 102 | var products = Data.getProductList(); 103 | 104 | var groupedByCategoryPrice = products.stream() 105 | .collect(Collectors.groupingBy(p -> p.category, 106 | Collectors.minBy(Comparator.comparing(p -> p.unitPrice)))); 107 | 108 | for(var key: groupedByCategoryPrice.keySet()) { 109 | var unitPrice = groupedByCategoryPrice.get(key).get().unitPrice; 110 | print("{Category: %s, CheapestPrice %.2f}", key, unitPrice); 111 | } 112 | } 113 | 114 | public static void Linq84() { 115 | print("TODO"); 116 | } 117 | 118 | public static void Linq85() { 119 | var numbers = new int []{ 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 120 | 121 | var maxNum = Arrays.stream(numbers).max().getAsInt(); 122 | 123 | print("The maximum number is %d.", maxNum); 124 | } 125 | 126 | public static void Linq86() { 127 | var words = new String[] { "cherry", "apple", "blueberry" }; 128 | 129 | var shortestWord = Arrays.stream(words) 130 | .mapToInt(w -> w.length()) 131 | .max() 132 | .getAsInt(); 133 | 134 | print("The longest word is %d characters long.", shortestWord); 135 | } 136 | 137 | public static void Linq87() { 138 | var products = Data.getProductList(); 139 | 140 | var groupedByCategoryPrice = products.stream() 141 | .collect(Collectors.groupingBy(p -> p.category, 142 | Collectors.maxBy(Comparator.comparing(p -> p.unitPrice)))); 143 | 144 | for(var key: groupedByCategoryPrice.keySet()) { 145 | var unitPrice = groupedByCategoryPrice.get(key).get().unitPrice; 146 | print("{Category: %s, MostExpensive %.2f}", key, unitPrice); 147 | } 148 | } 149 | 150 | public static void Linq88() { 151 | print("TODO"); 152 | } 153 | 154 | public static void Linq89() { 155 | var numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 156 | 157 | var averageNum = Arrays.stream(numbers).average().getAsDouble(); 158 | 159 | print("The averages number is %.2f." , averageNum); 160 | } 161 | 162 | public static void Linq90() { 163 | var words = new String[] { "cherry", "apple", "blueberry" }; 164 | 165 | var averageWordLength = Arrays.stream(words) 166 | .mapToInt(w -> w.length()) 167 | .average() 168 | .getAsDouble(); 169 | 170 | print("The shortest word is %f characters long.", averageWordLength); 171 | } 172 | 173 | public static void Linq91() { 174 | print("TODO"); 175 | } 176 | 177 | public static void Linq92() { 178 | var doubles = new double[] { 1.7, 2.3, 1.9, 4.1, 2.9 }; 179 | 180 | var product = Arrays.stream(doubles) 181 | .reduce((runningTotal, nextFactor) -> runningTotal * nextFactor) 182 | .getAsDouble(); 183 | 184 | print("Total product of all numbers: %f" , product); 185 | } 186 | 187 | public static void Linq93() { 188 | int startBalance = 100; 189 | 190 | var attemptedWithdrawals = new int[]{ 20, 10, 40, 50, 10, 70, 30 }; 191 | 192 | var endBalance = Arrays.stream(attemptedWithdrawals) 193 | .reduce(startBalance, 194 | (balance, nextWithdrawal) -> 195 | (nextWithdrawal <= balance) ? (balance - nextWithdrawal) : balance); 196 | 197 | print("Ending balance: %d", endBalance); 198 | } 199 | 200 | } 201 | -------------------------------------------------------------------------------- /src/csharp/linq-ordering/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel; 3 | using System.Linq; 4 | using linqshared; 5 | 6 | namespace linq_ordering 7 | { 8 | class Program: ProgramBase 9 | { 10 | static void Main(string[] args) 11 | { 12 | Linq28(); 13 | // Linq29(); 14 | // Linq30(); 15 | // Linq31(); 16 | // Linq32(); 17 | // Linq33(); 18 | // Linq34(); 19 | // Linq35(); 20 | // Linq36(); 21 | // Linq37(); 22 | // Linq38(); 23 | // Linq39(); 24 | } 25 | 26 | 27 | [Category("Ordering Operators")] 28 | [Description("This sample uses ordering to sort a list of words alphabetically.")] 29 | static void Linq28() 30 | { 31 | var words = new [] { "cherry", "apple", "blueberry" }; 32 | 33 | var sortedWords = words.OrderBy(w => w); 34 | 35 | Console.WriteLine("The sorted list of words:"); 36 | sortedWords.ForEach(Console.WriteLine); 37 | } 38 | 39 | [Category("Ordering Operators")] 40 | [Description("This sample uses ordering to sort a list of words by length.")] 41 | static void Linq29() 42 | { 43 | var words = new [] { "cherry", "apple", "blueberry" }; 44 | 45 | var sortedWords = words.OrderBy(w => w.Length); 46 | 47 | Console.WriteLine("The sorted list of words (by length):"); 48 | sortedWords.ForEach(Console.WriteLine); 49 | } 50 | 51 | [Category("Ordering Operators")] 52 | [Description("This sample uses ordering to sort a list of products by name.")] 53 | static void Linq30() 54 | { 55 | var products = GetProductList(); 56 | 57 | var sortedProducts = products.OrderBy(p => p.ProductName); 58 | 59 | ObjectDumper.Write(sortedProducts); 60 | } 61 | 62 | [Category("Ordering Operators")] 63 | [Description("This sample uses case-insensitive ordering to sort the words in an array.")] 64 | static void Linq31() 65 | { 66 | var words = new [] { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" }; 67 | 68 | var sortedWords = words.OrderBy(a => a, StringComparer.CurrentCultureIgnoreCase); 69 | 70 | ObjectDumper.Write(sortedWords); 71 | } 72 | 73 | [Category("Ordering Operators")] 74 | [Description("This sample uses reverse ordering to sort a list of doubles from highest to lowest.")] 75 | static void Linq32() 76 | { 77 | var doubles = new[]{ 1.7, 2.3, 1.9, 4.1, 2.9 }; 78 | 79 | var sortedDoubles = doubles.OrderByDescending(d => d); 80 | 81 | Console.WriteLine("The doubles from highest to lowest:"); 82 | sortedDoubles.ForEach(Console.WriteLine); 83 | } 84 | 85 | [Category("Ordering Operators")] 86 | [Description("This sample uses reverse ordering to sort a list of products by units in stock from highest to lowest.")] 87 | static void Linq33() 88 | { 89 | var products = GetProductList(); 90 | 91 | var sortedProducts = products.OrderByDescending(p => p.UnitsInStock); 92 | 93 | ObjectDumper.Write(sortedProducts); 94 | } 95 | 96 | [Category("Ordering Operators")] 97 | [Description("This sample uses reverse case-insensitive ordering to sort the words in an array.")] 98 | static void Linq34() 99 | { 100 | var words = new [] { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" }; 101 | 102 | var sortedWords = words.OrderByDescending(a => a, StringComparer.CurrentCultureIgnoreCase); 103 | 104 | ObjectDumper.Write(sortedWords); 105 | } 106 | 107 | [Category("Ordering Operators")] 108 | [Description("This sample uses nested ordering, first by length of their name, and then alphabetically by the name itself.")] 109 | static void Linq35() 110 | { 111 | var digits = new [] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 112 | 113 | var sortedDigits = digits 114 | .OrderBy(d => d.Length) 115 | .ThenBy(d => d); 116 | 117 | Console.WriteLine("Sorted digits:"); 118 | sortedDigits.ForEach(Console.WriteLine); 119 | } 120 | 121 | [Category("Ordering Operators")] 122 | [Description("This sample uses case-insensitive nested ordering, with a custom comparer to sort first by word length and then by a case-insensitive sort of the words in an array.")] 123 | static void Linq36() 124 | { 125 | var words = new [] { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" }; 126 | 127 | var sortedWords = words 128 | .OrderBy(a => a.Length) 129 | .ThenBy(a => a, StringComparer.CurrentCultureIgnoreCase); 130 | 131 | ObjectDumper.Write(sortedWords); 132 | } 133 | 134 | [Category("Ordering Operators")] 135 | [Description("This sample uses nested ordering to sort a list of products, first by category, and then by unit price, from highest to lowest.")] 136 | static void Linq37() 137 | { 138 | var products = GetProductList(); 139 | 140 | var sortedProducts = products 141 | .OrderBy(p => p.Category) 142 | .ThenByDescending(p => p.UnitPrice); 143 | 144 | ObjectDumper.Write(sortedProducts); 145 | } 146 | 147 | [Category("Ordering Operators")] 148 | [Description("This sample uses uses case-insensitive reverse nested ordering to sort first by word length and then by a case-insensitive descending sort of the words in an array.")] 149 | static void Linq38() 150 | { 151 | var words = new [] { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" }; 152 | 153 | var sortedWords = words 154 | .OrderBy(a => a.Length) 155 | .ThenByDescending(a => a, StringComparer.CurrentCultureIgnoreCase); 156 | 157 | ObjectDumper.Write(sortedWords); 158 | } 159 | 160 | [Category("Ordering Operators")] 161 | [Description("This sample uses reverse ordering 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.")] 162 | static void Linq39() 163 | { 164 | var digits = new [] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 165 | 166 | var reversedIDigits = digits 167 | .Where(d => d[1] == 'i') 168 | .Reverse(); 169 | 170 | Console.WriteLine("A backwards list of the digits with a second character of 'i':"); 171 | reversedIDigits.ForEach(Console.WriteLine); 172 | } 173 | 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /src/csharp/LinqSamples101.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "linq-restrictions", "linq-restrictions\linq-restrictions.csproj", "{7E711DE9-B44C-4AA7-B4AF-0518224B409B}" 5 | EndProject 6 | Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "linq-shared", "linq-shared\linq-shared.shproj", "{8326DE7B-F4BB-4F86-8B5D-440175C2F0D5}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "linq-projections", "linq-projections\linq-projections.csproj", "{A7A45499-8C49-4B74-91CE-D147C0D76250}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "linq-partitioning", "linq-partitioning\linq-partitioning.csproj", "{85B4306F-5BB5-4E06-B8E5-8B2254E93063}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "linq-ordering", "linq-ordering\linq-ordering.csproj", "{6860BB9E-6A74-4D4E-8D18-AB922034D9D2}" 13 | EndProject 14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "linq-grouping", "linq-grouping\linq-grouping.csproj", "{3FA4951F-4FF1-469C-838F-8C467B1EF467}" 15 | EndProject 16 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "linq-sets", "linq-sets\linq-sets.csproj", "{BF102498-14B9-48A5-B2A8-94B93A22879C}" 17 | EndProject 18 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "linq-conversion", "linq-conversion\linq-conversion.csproj", "{40755F95-871E-4469-9A30-2A2C727DACA7}" 19 | EndProject 20 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "linq-element", "linq-element\linq-element.csproj", "{91204610-6A4F-4D40-86FC-B413BE2B1E3A}" 21 | EndProject 22 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "linq-generation", "linq-generation\linq-generation.csproj", "{B9A21EFA-98D8-475D-A649-9F15F5C47D8E}" 23 | EndProject 24 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "linq-quantifiers", "linq-quantifiers\linq-quantifiers.csproj", "{1FC8ADD4-7394-4A72-8CB5-4AE5C111DAC9}" 25 | EndProject 26 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "linq-aggregate", "linq-aggregate\linq-aggregate.csproj", "{96ED0B27-654A-4D37-992A-183CD2BA15F6}" 27 | EndProject 28 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "linq-miscellaneous", "linq-miscellaneous\linq-miscellaneous.csproj", "{6D7DA36C-69C2-4B12-8BF3-00EC960C0021}" 29 | EndProject 30 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "linq-query", "linq-query\linq-query.csproj", "{B39EA685-84A6-466C-A3DF-B24D93326C44}" 31 | EndProject 32 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "linq-join", "linq-join\linq-join.csproj", "{254997F1-9B09-488B-AC6E-DFFE6791F3E3}" 33 | EndProject 34 | Global 35 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 36 | Debug|Any CPU = Debug|Any CPU 37 | Release|Any CPU = Release|Any CPU 38 | EndGlobalSection 39 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 40 | {7E711DE9-B44C-4AA7-B4AF-0518224B409B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 41 | {7E711DE9-B44C-4AA7-B4AF-0518224B409B}.Debug|Any CPU.Build.0 = Debug|Any CPU 42 | {7E711DE9-B44C-4AA7-B4AF-0518224B409B}.Release|Any CPU.ActiveCfg = Release|Any CPU 43 | {7E711DE9-B44C-4AA7-B4AF-0518224B409B}.Release|Any CPU.Build.0 = Release|Any CPU 44 | {A7A45499-8C49-4B74-91CE-D147C0D76250}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 45 | {A7A45499-8C49-4B74-91CE-D147C0D76250}.Debug|Any CPU.Build.0 = Debug|Any CPU 46 | {A7A45499-8C49-4B74-91CE-D147C0D76250}.Release|Any CPU.ActiveCfg = Release|Any CPU 47 | {A7A45499-8C49-4B74-91CE-D147C0D76250}.Release|Any CPU.Build.0 = Release|Any CPU 48 | {85B4306F-5BB5-4E06-B8E5-8B2254E93063}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 49 | {85B4306F-5BB5-4E06-B8E5-8B2254E93063}.Debug|Any CPU.Build.0 = Debug|Any CPU 50 | {85B4306F-5BB5-4E06-B8E5-8B2254E93063}.Release|Any CPU.ActiveCfg = Release|Any CPU 51 | {85B4306F-5BB5-4E06-B8E5-8B2254E93063}.Release|Any CPU.Build.0 = Release|Any CPU 52 | {6860BB9E-6A74-4D4E-8D18-AB922034D9D2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 53 | {6860BB9E-6A74-4D4E-8D18-AB922034D9D2}.Debug|Any CPU.Build.0 = Debug|Any CPU 54 | {6860BB9E-6A74-4D4E-8D18-AB922034D9D2}.Release|Any CPU.ActiveCfg = Release|Any CPU 55 | {6860BB9E-6A74-4D4E-8D18-AB922034D9D2}.Release|Any CPU.Build.0 = Release|Any CPU 56 | {3FA4951F-4FF1-469C-838F-8C467B1EF467}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 57 | {3FA4951F-4FF1-469C-838F-8C467B1EF467}.Debug|Any CPU.Build.0 = Debug|Any CPU 58 | {3FA4951F-4FF1-469C-838F-8C467B1EF467}.Release|Any CPU.ActiveCfg = Release|Any CPU 59 | {3FA4951F-4FF1-469C-838F-8C467B1EF467}.Release|Any CPU.Build.0 = Release|Any CPU 60 | {BF102498-14B9-48A5-B2A8-94B93A22879C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 61 | {BF102498-14B9-48A5-B2A8-94B93A22879C}.Debug|Any CPU.Build.0 = Debug|Any CPU 62 | {BF102498-14B9-48A5-B2A8-94B93A22879C}.Release|Any CPU.ActiveCfg = Release|Any CPU 63 | {BF102498-14B9-48A5-B2A8-94B93A22879C}.Release|Any CPU.Build.0 = Release|Any CPU 64 | {40755F95-871E-4469-9A30-2A2C727DACA7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 65 | {40755F95-871E-4469-9A30-2A2C727DACA7}.Debug|Any CPU.Build.0 = Debug|Any CPU 66 | {40755F95-871E-4469-9A30-2A2C727DACA7}.Release|Any CPU.ActiveCfg = Release|Any CPU 67 | {40755F95-871E-4469-9A30-2A2C727DACA7}.Release|Any CPU.Build.0 = Release|Any CPU 68 | {91204610-6A4F-4D40-86FC-B413BE2B1E3A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 69 | {91204610-6A4F-4D40-86FC-B413BE2B1E3A}.Debug|Any CPU.Build.0 = Debug|Any CPU 70 | {91204610-6A4F-4D40-86FC-B413BE2B1E3A}.Release|Any CPU.ActiveCfg = Release|Any CPU 71 | {91204610-6A4F-4D40-86FC-B413BE2B1E3A}.Release|Any CPU.Build.0 = Release|Any CPU 72 | {B9A21EFA-98D8-475D-A649-9F15F5C47D8E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 73 | {B9A21EFA-98D8-475D-A649-9F15F5C47D8E}.Debug|Any CPU.Build.0 = Debug|Any CPU 74 | {B9A21EFA-98D8-475D-A649-9F15F5C47D8E}.Release|Any CPU.ActiveCfg = Release|Any CPU 75 | {B9A21EFA-98D8-475D-A649-9F15F5C47D8E}.Release|Any CPU.Build.0 = Release|Any CPU 76 | {1FC8ADD4-7394-4A72-8CB5-4AE5C111DAC9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 77 | {1FC8ADD4-7394-4A72-8CB5-4AE5C111DAC9}.Debug|Any CPU.Build.0 = Debug|Any CPU 78 | {1FC8ADD4-7394-4A72-8CB5-4AE5C111DAC9}.Release|Any CPU.ActiveCfg = Release|Any CPU 79 | {1FC8ADD4-7394-4A72-8CB5-4AE5C111DAC9}.Release|Any CPU.Build.0 = Release|Any CPU 80 | {96ED0B27-654A-4D37-992A-183CD2BA15F6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 81 | {96ED0B27-654A-4D37-992A-183CD2BA15F6}.Debug|Any CPU.Build.0 = Debug|Any CPU 82 | {96ED0B27-654A-4D37-992A-183CD2BA15F6}.Release|Any CPU.ActiveCfg = Release|Any CPU 83 | {96ED0B27-654A-4D37-992A-183CD2BA15F6}.Release|Any CPU.Build.0 = Release|Any CPU 84 | {6D7DA36C-69C2-4B12-8BF3-00EC960C0021}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 85 | {6D7DA36C-69C2-4B12-8BF3-00EC960C0021}.Debug|Any CPU.Build.0 = Debug|Any CPU 86 | {6D7DA36C-69C2-4B12-8BF3-00EC960C0021}.Release|Any CPU.ActiveCfg = Release|Any CPU 87 | {6D7DA36C-69C2-4B12-8BF3-00EC960C0021}.Release|Any CPU.Build.0 = Release|Any CPU 88 | {B39EA685-84A6-466C-A3DF-B24D93326C44}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 89 | {B39EA685-84A6-466C-A3DF-B24D93326C44}.Debug|Any CPU.Build.0 = Debug|Any CPU 90 | {B39EA685-84A6-466C-A3DF-B24D93326C44}.Release|Any CPU.ActiveCfg = Release|Any CPU 91 | {B39EA685-84A6-466C-A3DF-B24D93326C44}.Release|Any CPU.Build.0 = Release|Any CPU 92 | {254997F1-9B09-488B-AC6E-DFFE6791F3E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 93 | {254997F1-9B09-488B-AC6E-DFFE6791F3E3}.Debug|Any CPU.Build.0 = Debug|Any CPU 94 | {254997F1-9B09-488B-AC6E-DFFE6791F3E3}.Release|Any CPU.ActiveCfg = Release|Any CPU 95 | {254997F1-9B09-488B-AC6E-DFFE6791F3E3}.Release|Any CPU.Build.0 = Release|Any CPU 96 | EndGlobalSection 97 | EndGlobal 98 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/src/main/java/support/Data.java: -------------------------------------------------------------------------------- 1 | package support; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import models.*; 5 | 6 | import java.io.File; 7 | import java.io.IOException; 8 | import java.util.Arrays; 9 | import java.util.List; 10 | 11 | public class Data { 12 | 13 | public static List getProductList() { 14 | Product[] products = new Product[]{ 15 | new Product(1, "Chai", "Beverages", 18.000, 39), 16 | new Product(2, "Chang", "Beverages", 19.000, 17), 17 | new Product(3, "Aniseed Syrup", "Condiments", 10.000, 13), 18 | new Product(4, "Chef Anton's Cajun Seasoning", "Condiments", 22.000, 53), 19 | new Product(5, "Chef Anton's Gumbo Mix", "Condiments", 21.350, 0), 20 | new Product(6, "Grandma's Boysenberry Spread", "Condiments", 25.000, 120), 21 | new Product(7, "Uncle Bob's Organic Dried Pears", "Produce", 30.000, 15), 22 | new Product(8, "Northwoods Cranberry Sauce", "Condiments", 40.000, 6), 23 | new Product(9, "Mishi Kobe Niku", "Meat/Poultry", 97.000, 29), 24 | new Product(10, "Ikura", "Seafood", 31.000, 31), 25 | new Product(11, "Queso Cabrales", "Dairy Products", 21.000, 22), 26 | new Product(12, "Queso Manchego La Pastora", "Dairy Products", 38.000, 86), 27 | new Product(13, "Konbu", "Seafood", 6.000, 24), 28 | new Product(14, "Tofu", "Produce", 23.250, 35), 29 | new Product(15, "Genen Shouyu", "Condiments", 15.500, 39), 30 | new Product(16, "Pavlova", "Confections", 17.450, 29), 31 | new Product(17, "Alice Mutton", "Meat/Poultry", 39.000, 0), 32 | new Product(18, "Carnarvon Tigers", "Seafood", 62.500, 42), 33 | new Product(19, "Teatime Chocolate Biscuits", "Confections", 9.200, 25), 34 | new Product(20, "Sir Rodney's Marmalade", "Confections", 81.000, 40), 35 | new Product(21, "Sir Rodney's Scones", "Confections", 10.000, 3), 36 | new Product(22, "Gustaf's Kn\u00e4ckebr\u00f6d", "Grains/Cereals", 21.000, 104), 37 | new Product(23, "Tunnbr\u00f6d", "Grains/Cereals", 9.000, 61), 38 | new Product(24, "Guaran\u00e1 Fant\u00e1stica", "Beverages", 4.500, 20), 39 | new Product(25, "NuNuCa Nu\u00df-Nougat-Creme", "Confections", 14.000, 76), 40 | new Product(26, "Gumb\u00e4r Gummib\u00e4rchen", "Confections", 31.230, 15), 41 | new Product(27, "Schoggi Schokolade", "Confections", 43.900, 49), 42 | new Product(28, "R\u00f6ssle Sauerkraut", "Produce", 45.600, 26), 43 | new Product(29, "Th\u00fcringer Rostbratwurst", "Meat/Poultry", 123.790, 0), 44 | new Product(30, "Nord-Ost Matjeshering", "Seafood", 25.890, 10), 45 | new Product(31, "Gorgonzola Telino", "Dairy Products", 12.500, 0), 46 | new Product(32, "Mascarpone Fabioli", "Dairy Products", 32.000, 9), 47 | new Product(33, "Geitost", "Dairy Products", 2.500, 112), 48 | new Product(34, "Sasquatch Ale", "Beverages", 14.000, 111), 49 | new Product(35, "Steeleye Stout", "Beverages", 18.000, 20), 50 | new Product(36, "Inlagd Sill", "Seafood", 19.000, 112), 51 | new Product(37, "Gravad lax", "Seafood", 26.000, 11), 52 | new Product(38, "C\u00f4te de Blaye", "Beverages", 263.500, 17), 53 | new Product(39, "Chartreuse verte", "Beverages", 18.000, 69), 54 | new Product(40, "Boston Crab Meat", "Seafood", 18.400, 123), 55 | new Product(41, "Jack's New England Clam Chowder", "Seafood", 9.650, 85), 56 | new Product(42, "Singaporean Hokkien Fried Mee", "Grains/Cereals", 14.000, 26), 57 | new Product(43, "Ipoh Coffee", "Beverages", 46.000, 17), 58 | new Product(44, "Gula Malacca", "Condiments", 19.450, 27), 59 | new Product(45, "Rogede sild", "Seafood", 9.500, 5), 60 | new Product(46, "Spegesild", "Seafood", 12.000, 95), 61 | new Product(47, "Zaanse koeken", "Confections", 9.500, 36), 62 | new Product(48, "Chocolade", "Confections", 12.750, 15), 63 | new Product(49, "Maxilaku", "Confections", 20.000, 10), 64 | new Product(50, "Valkoinen suklaa", "Confections", 16.250, 65), 65 | new Product(51, "Manjimup Dried Apples", "Produce", 53.000, 20), 66 | new Product(52, "Filo Mix", "Grains/Cereals", 7.000, 38), 67 | new Product(53, "Perth Pasties", "Meat/Poultry", 32.800, 0), 68 | new Product(54, "Tourti\u00e8re", "Meat/Poultry", 7.450, 21), 69 | new Product(55, "P\u00e2t\u00e9 chinois", "Meat/Poultry", 24.000, 115), 70 | new Product(56, "Gnocchi di nonna Alice", "Grains/Cereals", 38.000, 21), 71 | new Product(57, "Ravioli Angelo", "Grains/Cereals", 19.500, 36), 72 | new Product(58, "Escargots de Bourgogne", "Seafood", 13.250, 62), 73 | new Product(59, "Raclette Courdavault", "Dairy Products", 55.000, 79), 74 | new Product(60, "Camembert Pierrot", "Dairy Products", 34.000, 19), 75 | new Product(61, "Sirop d'\u00e9rable", "Condiments", 28.500, 113), 76 | new Product(62, "Tarte au sucre", "Confections", 49.300, 17), 77 | new Product(63, "Vegie-spread", "Condiments", 43.900, 24), 78 | new Product(64, "Wimmers gute Semmelkn\u00f6del", "Grains/Cereals", 33.250, 22), 79 | new Product(65, "Louisiana Fiery Hot Pepper Sauce", "Condiments", 21.050, 76), 80 | new Product(66, "Louisiana Hot Spiced Okra", "Condiments", 17.000, 4), 81 | new Product(67, "Laughing Lumberjack Lager", "Beverages", 14.000, 52), 82 | new Product(68, "Scottish Longbreads", "Confections", 12.500, 6), 83 | new Product(69, "Gudbrandsdalsost", "Dairy Products", 36.000, 26), 84 | new Product(70, "Outback Lager", "Beverages", 15.000, 15), 85 | new Product(71, "Flotemysost", "Dairy Products", 21.500, 26), 86 | new Product(72, "Mozzarella di Giovanni", "Dairy Products", 34.800, 14), 87 | new Product(73, "R\u00f6d Kaviar", "Seafood", 15.000, 101), 88 | new Product(74, "Longlife Tofu", "Produce", 10.000, 4), 89 | new Product(75, "Rh\u00f6nbr\u00e4u Klosterbier", "Beverages", 7.750, 125), 90 | new Product(76, "Lakkalik\u00f6\u00f6ri", "Beverages", 18.000, 57), 91 | new Product(77, "Original Frankfurter gr\u00fcne So\u00dfe", "Condiments", 13.000, 32) 92 | }; 93 | 94 | return Arrays.asList(products); 95 | } 96 | 97 | public static List getCustomerList() { 98 | ObjectMapper objectMapper = new ObjectMapper(); 99 | String dir = System.getProperty("user.dir"); 100 | File file = new File(dir + "/../../../Customers.json"); 101 | 102 | Customers result = null; 103 | try { 104 | result = objectMapper.readValue(file, Customers.class); 105 | 106 | result.customers.forEach(c -> { 107 | if (c.ordersList != null) { 108 | c.orders = c.ordersList.orderList; 109 | } 110 | }); 111 | } catch (IOException e) { 112 | e.printStackTrace(); 113 | } 114 | 115 | return result.customers; 116 | } 117 | 118 | } 119 | -------------------------------------------------------------------------------- /src/java/LinqSamples101/src/main/java/linq/LinqProjections.java: -------------------------------------------------------------------------------- 1 | package linq; 2 | 3 | import models.Customer; 4 | import models.Order; 5 | import support.Data; 6 | 7 | import java.util.*; 8 | import java.util.stream.Collectors; 9 | import java.util.stream.IntStream; 10 | 11 | import static support.Data.getCustomerList; 12 | 13 | public class LinqProjections extends LinqBase { 14 | 15 | public static void Linq6() { 16 | var numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 17 | 18 | var lownumbers = Arrays.stream(numbers) 19 | .boxed() 20 | .map(n -> n +1); 21 | 22 | print("Numbers +1:"); 23 | lownumbers.forEach(System.out::println); 24 | } 25 | 26 | public static void Linq7() { 27 | var products = Data.getProductList(); 28 | 29 | var productNames = products.stream() 30 | .map(p -> p.productName); 31 | 32 | print("Product Names:"); 33 | productNames.forEach(System.out::println); 34 | } 35 | 36 | public static void Linq8() { 37 | var numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 38 | var strings = new String[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 39 | 40 | var stringNums = Arrays.stream(numbers) 41 | .boxed() 42 | .map(n -> strings[n]); 43 | 44 | print("Number strings:"); 45 | stringNums.forEach(System.out::println); 46 | } 47 | 48 | public static void Linq9() { 49 | var words = new String[] { "aPPLE", "BlUeBeRrY", "cHeRry" }; 50 | 51 | var upperLowerWords = Arrays.stream(words) 52 | .map(w -> new Object() { 53 | String upper = w.toUpperCase(); 54 | String lower = w.toLowerCase(); 55 | }); 56 | 57 | upperLowerWords.forEach(word -> print("Uppercase: %s, Lowercase: %s", word.upper, word.lower)); 58 | } 59 | 60 | public static void Linq10() { 61 | var numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 62 | var strings = new String[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 63 | 64 | var digitOddEvens = Arrays.stream(numbers) 65 | .boxed() 66 | .map(n -> new Object() { 67 | String Digit = strings[n]; 68 | Boolean Even = n % 2 == 0; 69 | }); 70 | 71 | digitOddEvens.forEach(o -> print("The digit %s is %s", o.Digit, o.Even ? "even" : "odd")); 72 | } 73 | 74 | public static void Linq11() { 75 | var products = Data.getProductList(); 76 | 77 | var productInfos = products.stream() 78 | .map(p -> new Object() { 79 | String ProductName = p.productName; 80 | String Category = p.category; 81 | Double Price = p.unitPrice; 82 | }); 83 | 84 | print("Product Info:"); 85 | productInfos.forEach(product -> print("%s is in the category %s and costs %.2f per unit.", product.ProductName, product.Category, product.Price)); 86 | } 87 | 88 | public static void Linq12() { 89 | var numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 90 | 91 | var numsInPlace = IntStream.range(0, numbers.length) 92 | .mapToObj(index -> new Object() { 93 | int Num = numbers[index]; 94 | Boolean InPlace = numbers[index] == index; 95 | }); 96 | 97 | print("Number: In-place?"); 98 | numsInPlace.forEach(n -> print("%d: %s" , n.Num, n.InPlace)); 99 | } 100 | 101 | public static void Linq13() { 102 | var numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 103 | var digits = new String[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 104 | 105 | var lowNums = Arrays.stream(numbers) 106 | .boxed() 107 | .filter(n -> n < 5) 108 | .map(n -> digits[n]); 109 | 110 | print("Numbers < 5:"); 111 | lowNums.forEach(System.out::println); 112 | } 113 | 114 | public static void Linq14() { 115 | var numbersA = new Integer[] { 0, 2, 4, 5, 6, 8, 9 }; 116 | var numbersB = new Integer[]{ 1, 3, 5, 7, 8 }; 117 | System.out.println("Pairs where a < b:"); 118 | Arrays.stream(numbersA) 119 | .flatMap(a -> Arrays.stream(numbersB).map(b -> new Object(){ 120 | Integer numberA = a; Integer numberB = b; 121 | })) 122 | .filter(pair -> pair.numberA < pair.numberB) 123 | .forEach(pair -> System.out.println(pair.numberA + " is less than "+ pair.numberB)); 124 | } 125 | 126 | public static void Linq15() { 127 | List customers = Data.getCustomerList(); 128 | customers.stream() 129 | .filter(c -> c.orders != null && c.orders.size() > 0) 130 | .flatMap(c -> c.orders.stream().map(o -> new Object(){ 131 | final String customerID = c.customerId; 132 | final Integer orderId = o.orderId; 133 | final Double total = o.total; 134 | })) 135 | .filter(o -> o.total < 500.00) 136 | .forEach(o -> System.out.println("{CustomerId: " + o.customerID + 137 | ", OrderId: " + o.orderId + 138 | ", Total: " + o.total)); 139 | } 140 | 141 | public static void Linq16() { 142 | List customers = Data.getCustomerList(); 143 | Date comparisonDate = new GregorianCalendar(1998, Calendar.JANUARY, 1).getTime(); 144 | customers.stream() 145 | .filter(c -> c.orders != null && c.orders.size() > 0) 146 | .flatMap(c -> c.orders.stream().map(o -> new Object(){ 147 | final String customerID = c.customerId; 148 | final Integer orderId = o.orderId; 149 | final Date orderDate = o.orderDate; 150 | })) 151 | .filter(o -> o.orderDate.compareTo(comparisonDate) >= 0 ) 152 | .forEach(o -> System.out.println("{CustomerId: " + o.customerID + 153 | ", OrderId: " + o.orderId + 154 | ", OrderDate: " + o.orderDate)); 155 | } 156 | 157 | public static void Linq17() { 158 | List customers = Data.getCustomerList(); 159 | customers.stream() 160 | .filter(c -> c.orders != null && c.orders.size() > 0) 161 | .flatMap(c -> c.orders.stream().map(o -> new Object(){ 162 | final String customerID = c.customerId; 163 | final Integer orderId = o.orderId; 164 | final Double total = o.total; 165 | })) 166 | .filter(o -> o.total > 2000 ) 167 | .forEach(o -> System.out.println("{CustomerId: " + o.customerID + 168 | ", OrderId: " + o.orderId + 169 | ", Total: " + o.total)); 170 | } 171 | 172 | public static void Linq18() { 173 | List customers = Data.getCustomerList(); 174 | var cutoffDate = new GregorianCalendar(1997, 1, 1).getTime(); 175 | customers.stream() 176 | .filter(c -> c.orders != null && c.orders.size() > 0) 177 | .filter(c -> Objects.equals(c.region, "WA")) 178 | .flatMap(c -> c.orders.stream().map(o -> new Object(){ 179 | final Customer customer = c; 180 | final Order order = o; 181 | })) 182 | .filter(o -> o.order.orderDate.compareTo(cutoffDate) >= 0 ) 183 | .map(o -> new Object(){ 184 | final String customerID = o.customer.customerId; 185 | final Integer orderId = o.order.orderId; 186 | final String region = o.customer.region; 187 | }) 188 | .forEach(o -> System.out.println("{CustomerId: " + o.customerID + 189 | ", OrderId: " + o.orderId + 190 | ", Region: " + o.region)); 191 | } 192 | 193 | public static void Linq19() { 194 | var customers = new ArrayList<>(Data.getCustomerList()); 195 | IntStream.range(0, customers.size()) 196 | .filter(i -> customers.get(i).orders != null) 197 | .mapToObj(i -> customers.get(i).orders.stream() 198 | .map(o -> new Object(){ 199 | final int index = i +1; 200 | final Integer orderID = o.orderId; 201 | })) 202 | .flatMap(s -> s) 203 | .forEach(o -> System.out.println("Customer " + o.index + 204 | " has an order with OrderID " + o.orderID)); 205 | } 206 | 207 | 208 | } 209 | -------------------------------------------------------------------------------- /src/csharp/linq-projections/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel; 3 | using linqshared; 4 | using System.Linq; 5 | using System.Globalization; 6 | 7 | namespace linq_projections 8 | { 9 | class Program : ProgramBase 10 | { 11 | static void Main(string[] args) 12 | { 13 | Linq6(); 14 | // Linq7(); 15 | // Linq8(); 16 | // Linq9(); 17 | // Linq10(); 18 | // Linq11(); 19 | // Linq12(); 20 | // Linq13(); 21 | // Linq14(); 22 | // Linq15(); 23 | // Linq16(); 24 | // Linq17(); 25 | // Linq18(); 26 | // Linq19(); 27 | } 28 | 29 | [Category("Projection Operators")] 30 | [Description("This sample projects a sequence of ints 1+ higher than those in an existing array of ints.")] 31 | static void Linq6() 32 | { 33 | var numbers = new[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 34 | 35 | var numsPlusOne = numbers.Select(n => n + 1); 36 | 37 | Console.WriteLine("Numbers + 1:"); 38 | numsPlusOne.ForEach(Console.WriteLine); 39 | } 40 | 41 | [Category("Projection Operators")] 42 | [Description("This sample projects a sequence of just the names of a list of products.")] 43 | static void Linq7() 44 | { 45 | var products = GetProductList(); 46 | 47 | var productNames = products.Select(p => p.ProductName); 48 | 49 | Console.WriteLine("Product Names:"); 50 | productNames.ForEach(Console.WriteLine); 51 | } 52 | 53 | [Category("Projection Operators")] 54 | [Description("This sample projects a sequence of strings representing the text version of a sequence of integers.")] 55 | static void Linq8() 56 | { 57 | var numbers = new[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 58 | var strings = new [] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 59 | 60 | var textNums = numbers.Select(n => strings[n]); 61 | 62 | Console.WriteLine("Number strings:"); 63 | textNums.ForEach(Console.WriteLine); 64 | } 65 | 66 | [Category("Projection Operators")] 67 | [Description("This sample projects a sequence of the uppercase and lowercase versions of each word in the original array.")] 68 | static void Linq9() 69 | { 70 | var words = new[] { "aPPLE", "BlUeBeRrY", "cHeRry" }; 71 | 72 | var upperLowerWords = words.Select(w => 73 | new 74 | { 75 | Upper = w.ToUpper(), 76 | Lower = w.ToLower() 77 | }); 78 | 79 | upperLowerWords.ForEach(ul => Console.WriteLine($"Uppercase: {ul.Upper}, Lowercase: {ul.Lower}")); 80 | } 81 | 82 | [Category("Projection Operators")] 83 | [Description("This sample projects a sequence containing text representations of digits and whether their length is even or odd.")] 84 | static void Linq10() 85 | { 86 | var numbers = new[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 87 | var strings = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 88 | 89 | var digitOddEvens = numbers.Select(n => 90 | new 91 | { 92 | Digit = strings[n], 93 | Even = (n % 2 == 0) 94 | }); 95 | 96 | digitOddEvens.ForEach(d => Console.WriteLine($"The digit {d.Digit} is {(d.Even ? "even" : "odd")}.")); 97 | } 98 | 99 | [Category("Projection Operators")] 100 | [Description("This sample projects a sequence containing some properties of Products, including UnitPrice which is renamed to Price in the resulting type.")] 101 | static void Linq11() 102 | { 103 | var products = GetProductList(); 104 | 105 | var productInfos = products.Select(p => 106 | new 107 | { 108 | p.ProductName, 109 | p.Category, 110 | Price = p.UnitPrice 111 | }); 112 | 113 | Console.WriteLine("Product Info:"); 114 | productInfos.ForEach(productInfo => Console.WriteLine($"{productInfo.ProductName} is in the category {productInfo.Category} and costs {productInfo.Price} per unit.")); 115 | } 116 | 117 | 118 | [Category("Projection Operators")] 119 | [Description("This sample uses an indexed projection to determine if the value of integers in an array match their position in the array.")] 120 | static void Linq12() 121 | { 122 | var numbers = new[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 123 | 124 | var numsInPlace = numbers.Select((num, index) => 125 | new 126 | { 127 | Num = num, 128 | InPlace = (num == index) 129 | }); 130 | 131 | Console.WriteLine("Number: In-place?"); 132 | numsInPlace.ForEach(n => Console.WriteLine($"{n.Num}: {n.InPlace}")); 133 | } 134 | 135 | [Category("Projection Operators")] 136 | [Description("This sample first filters, then projects to make a simple query that returns the text form of each digit less than 5.")] 137 | static void Linq13() 138 | { 139 | var numbers = new []{ 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 140 | var digits = new [] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 141 | 142 | var lowNums = numbers 143 | .Where(n => n < 5) 144 | .Select(n => digits[n]); 145 | 146 | Console.WriteLine("Numbers < 5:"); 147 | lowNums.ForEach(Console.WriteLine); 148 | } 149 | 150 | [Category("Projection Operators")] 151 | [Description("This sample projects a combination of 2 source arrays, then filters all pairs of numbers from both arrays such that the number from numbersA is less than the number from numbersB.")] 152 | static void Linq14() 153 | { 154 | var numbersA = new [] { 0, 2, 4, 5, 6, 8, 9 }; 155 | var numbersB = new []{ 1, 3, 5, 7, 8 }; 156 | 157 | var pairs = numbersA 158 | .SelectMany(a => numbersB, (a, b) => new { a, b }) 159 | .Where(x => x.a < x.b); 160 | 161 | Console.WriteLine("Pairs where a < b:"); 162 | pairs.ForEach(pair => Console.WriteLine("{0} is less than {1}", pair.a, pair.b)); 163 | } 164 | 165 | [Category("Projection Operators")] 166 | [Description("This sample uses a nested projection to flatten the customer orders, then filtes the order total is less than 500.00.")] 167 | static void Linq15() 168 | { 169 | var customers = GetCustomerList(); 170 | 171 | var orders = customers 172 | .SelectMany(customer => customer.Orders, (customer, order) => new { customer, order }) 173 | .Where(x => x.order.Total < 500.00M) 174 | .Select(x => 175 | new 176 | { 177 | x.customer.CustomerID, 178 | x.order.OrderID, 179 | x.order.Total 180 | }); 181 | 182 | ObjectDumper.Write(orders); 183 | } 184 | 185 | [Category("Projection Operators")] 186 | [Description("This sample uses a nested projection to flatten the customer orders, the filters all orders that was made in 1998 or later.")] 187 | static void Linq16() 188 | { 189 | var customers = GetCustomerList(); 190 | 191 | var orders = customers 192 | .SelectMany(customer => customer.Orders, (customer, order) => new { customer, order }) 193 | .Where(x => x.order.OrderDate >= new DateTime(1998, 1, 1)) 194 | .Select(x => 195 | new 196 | { 197 | x.customer.CustomerID, 198 | x.order.OrderID, 199 | x.order.OrderDate 200 | }); 201 | 202 | ObjectDumper.Write(orders); 203 | } 204 | 205 | [Category("Projection Operators")] 206 | [Description("This sample uses a nested projection to flatten the customer orders, then filters the orders where the order total is greater than 2000.00.")] 207 | static void Linq17() 208 | { 209 | var customers = GetCustomerList(); 210 | 211 | var orders = customers 212 | .SelectMany(customer => customer.Orders, (customer, order) => new { customer, order }) 213 | .Where(x => x.order.Total >= 2000.00M) 214 | .Select(x => 215 | new 216 | { 217 | x.customer.CustomerID, 218 | x.order.OrderID, 219 | x.order.Total 220 | }); 221 | 222 | ObjectDumper.Write(orders); 223 | } 224 | 225 | [Category("Projection Operators")] 226 | [Description("This sample fist filters on all Customers in Washington, then uses a nested projection to flatten the customer orders, then filtering on all orders greater than the cut-off date")] 227 | static void Linq18() 228 | { 229 | var customers = GetCustomerList(); 230 | 231 | var cutoffDate = new DateTime(1997, 1, 1); 232 | 233 | var orders = customers 234 | .Where(c => c.Region == "WA") 235 | .SelectMany(customer => customer.Orders, (customer, order) => new { customer, order }) 236 | .Where(x => x.order.OrderDate >= cutoffDate) 237 | .Select(x => 238 | new 239 | { 240 | x.customer.CustomerID, 241 | x.customer.Region, 242 | x.order.OrderID 243 | }); 244 | 245 | ObjectDumper.Write(orders); 246 | } 247 | 248 | [Category("Projection Operators")] 249 | [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.")] 250 | static void Linq19() 251 | { 252 | var customers = GetCustomerList(); 253 | 254 | var customerOrders = 255 | customers.SelectMany( 256 | (cust, custIndex) => 257 | cust.Orders.Select(o => $"Customer #{custIndex + 1}) has an order with OrderID {o.OrderID}")); 258 | 259 | ObjectDumper.Write(customerOrders); 260 | } 261 | } 262 | } -------------------------------------------------------------------------------- /src/csharp/linq-aggregate/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel; 3 | using System.Linq; 4 | using linqshared; 5 | 6 | namespace linq_aggregate 7 | { 8 | class Program : ProgramBase 9 | { 10 | static void Main(string[] args) 11 | { 12 | Linq73(); 13 | // Linq74(); 14 | // Linq76(); 15 | // Linq77(); 16 | // Linq78(); 17 | // Linq79(); 18 | // Linq80(); 19 | // Linq81(); 20 | // Linq82(); 21 | // Linq83(); 22 | // Linq84(); 23 | // Linq85(); 24 | // Linq86(); 25 | // Linq87(); 26 | // Linq88(); 27 | // Linq89(); 28 | // Linq90(); 29 | // Linq91(); 30 | // Linq92(); 31 | // Linq93(); 32 | 33 | } 34 | 35 | [Category("Aggregate Operators")] 36 | [Description("This sample gets the number of unique prime factors of 300.")] 37 | static void Linq73() 38 | { 39 | var primeFactorsOf300 = new [] { 2, 2, 3, 5, 5 }; 40 | 41 | var uniqueFactors = primeFactorsOf300.Distinct().Count(); 42 | 43 | Console.WriteLine($"There are {uniqueFactors} unique prime factors of 300."); 44 | } 45 | 46 | [Category("Aggregate Operators")] 47 | [Description("This sample gets the number of odd ints in the array.")] 48 | static void Linq74() 49 | { 50 | var numbers = new [] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 51 | 52 | var oddNumbers = numbers.Count(n => n % 2 == 1); 53 | 54 | Console.WriteLine($"There are {oddNumbers} odd numbers in the list."); 55 | } 56 | 57 | [Category("Aggregate Operators")] 58 | [Description("This sample uses returns a list of customers and how many orders each has.")] 59 | static void Linq76() 60 | { 61 | var customers = GetCustomerList(); 62 | 63 | var orderCounts = customers 64 | .Select(cust => 65 | new 66 | { 67 | cust.CustomerID, 68 | OrderCount = cust.Orders.Count() 69 | }); 70 | 71 | ObjectDumper.Write(orderCounts); 72 | } 73 | 74 | [Category("Aggregate Operators")] 75 | [Description("This sample uses returns a list of categories and how many products each has.")] 76 | static void Linq77() 77 | { 78 | var products = GetProductList(); 79 | 80 | var categoryCounts = products 81 | .GroupBy(prod => prod.Category) 82 | .Select(prodGroup => 83 | new 84 | { 85 | Category = prodGroup.Key, 86 | ProductCount = prodGroup.Count() 87 | }); 88 | 89 | ObjectDumper.Write(categoryCounts); 90 | } 91 | 92 | [Category("Aggregate Operators")] 93 | [Description("This sample uses adds all the numbers in an array.")] 94 | static void Linq78() 95 | { 96 | var numbers = new [] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 97 | 98 | var numSum = numbers.Sum(); 99 | 100 | Console.WriteLine($"The sum of the numbers is {numSum}."); 101 | } 102 | 103 | [Category("Aggregate Operators")] 104 | [Description("This sample gets the total number of characters of all words in the array.")] 105 | static void Linq79() 106 | { 107 | var words = new [] { "cherry", "apple", "blueberry" }; 108 | 109 | var totalChars = words.Sum(w => w.Length); 110 | 111 | Console.WriteLine($"There are a total of {totalChars} characters in these words."); 112 | } 113 | 114 | [Category("Aggregate Operators")] 115 | [Description("This sample gets the total units in stock for each product category.")] 116 | static void Linq80() 117 | { 118 | var products = GetProductList(); 119 | 120 | var categories = products 121 | .GroupBy(prod => prod.Category) 122 | .Select(prodGroup => 123 | new 124 | { 125 | Category = prodGroup.Key, 126 | TotalUnitsInStock = prodGroup.Sum(p => p.UnitsInStock) 127 | }); 128 | 129 | ObjectDumper.Write(categories); 130 | } 131 | 132 | [Category("Aggregate Operators")] 133 | [Description("This sample uses gets the lowest number in an array.")] 134 | static void Linq81() 135 | { 136 | var numbers = new []{ 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 137 | 138 | var minNum = numbers.Min(); 139 | 140 | Console.WriteLine($"The minimum number is {minNum}."); 141 | } 142 | 143 | [Category("Aggregate Operators")] 144 | [Description("This sample uses gets the length of the shortest word in an array.")] 145 | static void Linq82() 146 | { 147 | var words = new [] { "cherry", "apple", "blueberry" }; 148 | 149 | var shortestWord = words.Min(w => w.Length); 150 | 151 | Console.WriteLine($"The shortest word is {shortestWord} characters long."); 152 | } 153 | 154 | [Category("Aggregate Operators")] 155 | [Description("This sample uses gets the cheapest price among each category's products.")] 156 | static void Linq83() 157 | { 158 | var products = GetProductList(); 159 | 160 | var categories = products 161 | .GroupBy(prod => prod.Category) 162 | .Select(prodGroup => 163 | new 164 | { 165 | Category = prodGroup.Key, 166 | CheapestPrice = prodGroup.Min(p => p.UnitPrice) 167 | }); 168 | 169 | ObjectDumper.Write(categories); 170 | } 171 | 172 | [Category("Aggregate Operators")] 173 | [Description("This sample gets the products with the lowest price in each category.")] 174 | static void Linq84() 175 | { 176 | var products = GetProductList(); 177 | 178 | var categories = products.GroupBy(prod => prod.Category) 179 | .Select(prodGroup => new {prodGroup, minPrice = prodGroup.Min(p => p.UnitPrice)}) 180 | .Select(x => 181 | new 182 | { 183 | Category = x.prodGroup.Key, 184 | CheapestProducts = x.prodGroup.Where(p => p.UnitPrice == x.minPrice) 185 | }); 186 | 187 | ObjectDumper.Write(categories, 1); 188 | } 189 | 190 | [Category("Aggregate Operators")] 191 | [Description("This sample gets the highest number in an array. Note that the method returns a single value.")] 192 | static void Linq85() 193 | { 194 | var numbers = new []{ 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 195 | 196 | var maxNum = numbers.Max(); 197 | 198 | Console.WriteLine($"The maximum number is {maxNum}."); 199 | } 200 | 201 | [Category("Aggregate Operators")] 202 | [Description("This sample gets the length of the longest word in an array.")] 203 | static void Linq86() 204 | { 205 | var words = new [] { "cherry", "apple", "blueberry" }; 206 | 207 | var longestLength = words.Max(w => w.Length); 208 | 209 | Console.WriteLine($"The longest word is {longestLength} characters long."); 210 | } 211 | 212 | [Category("Aggregate Operators")] 213 | [Description("This sample gets the most expensive price among each category's products.")] 214 | static void Linq87() 215 | { 216 | var products = GetProductList(); 217 | 218 | var categories = products 219 | .GroupBy(prod => prod.Category) 220 | .Select(prodGroup => 221 | new 222 | { 223 | Category = prodGroup.Key, 224 | MostExpensivePrice = prodGroup.Max(p => p.UnitPrice) 225 | }); 226 | 227 | ObjectDumper.Write(categories); 228 | } 229 | 230 | [Category("Aggregate Operators")] 231 | [Description("This sample gets the products with the most expensive price in each category.")] 232 | static void Linq88() 233 | { 234 | var products = GetProductList(); 235 | 236 | var categories = products.GroupBy(prod => prod.Category) 237 | .Select(prodGroup => new {prodGroup, maxPrice = prodGroup.Max(p => p.UnitPrice)}) 238 | .Select(x => 239 | new 240 | { 241 | Category = x.prodGroup.Key, 242 | MostExpensiveProducts = x.prodGroup.Where(p => p.UnitPrice == x.maxPrice) 243 | }); 244 | 245 | ObjectDumper.Write(categories, 1); 246 | } 247 | 248 | [Category("Aggregate Operators")] 249 | [Description("This sample gets the average of all numbers in an array.")] 250 | static void Linq89() 251 | { 252 | var numbers = new [] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 253 | 254 | var averageNum = numbers.Average(); 255 | 256 | Console.WriteLine($"The average number is {averageNum}."); 257 | } 258 | 259 | 260 | [Category("Aggregate Operators")] 261 | [Description("This sample gets the average length of the words in the array.")] 262 | static void Linq90() 263 | { 264 | var words = new [] { "cherry", "apple", "blueberry" }; 265 | 266 | var averageLength = words.Average(w => w.Length); 267 | 268 | Console.WriteLine($"The average word length is {averageLength} characters."); 269 | } 270 | 271 | [Category("Aggregate Operators")] 272 | [Description("This sample gets the average price of each category's products.")] 273 | static void Linq91() 274 | { 275 | var products = GetProductList(); 276 | 277 | var categories = products 278 | .GroupBy(prod => prod.Category) 279 | .Select(prodGroup => 280 | new 281 | { 282 | Category = prodGroup.Key, 283 | AveragePrice = prodGroup.Average(p => p.UnitPrice) 284 | }); 285 | 286 | ObjectDumper.Write(categories); 287 | } 288 | 289 | [Category("Aggregate Operators")] 290 | [Description("This sample uses creates a running product on the array that calculates the total product of all elements.")] 291 | static void Linq92() 292 | { 293 | var doubles = new [] { 1.7, 2.3, 1.9, 4.1, 2.9 }; 294 | 295 | var product = doubles.Aggregate((runningProduct, nextFactor) => runningProduct * nextFactor); 296 | 297 | Console.WriteLine($"Total product of all numbers: {product}"); 298 | } 299 | 300 | [Category("Aggregate Operators")] 301 | [Description("This sample uses to creates a running account balance that subtracts each withdrawal from the initial balance of 100, as long as the balance never drops below 0.")] 302 | static void Linq93() 303 | { 304 | var startBalance = 100.0; 305 | 306 | var attemptedWithdrawals = new []{ 20, 10, 40, 50, 10, 70, 30 }; 307 | 308 | var endBalance = attemptedWithdrawals 309 | .Aggregate(startBalance, 310 | (balance, nextWithdrawal) => 311 | ((nextWithdrawal <= balance) ? (balance - nextWithdrawal) : balance)); 312 | 313 | Console.WriteLine($"Ending balance: {endBalance}"); 314 | } 315 | 316 | } 317 | } 318 | -------------------------------------------------------------------------------- /src/csharp/linq-shared/ProgramBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Xml.Linq; 4 | using System.Linq; 5 | 6 | namespace linqshared 7 | { 8 | public class ProgramBase 9 | { 10 | public static IEnumerable GetProductList() 11 | { 12 | return new []{ 13 | new Product { ProductID = 1, ProductName = "Chai", Category = "Beverages", UnitPrice = 18.0000M, UnitsInStock = 39 }, 14 | new Product { ProductID = 2, ProductName = "Chang", Category = "Beverages", UnitPrice = 19.0000M, UnitsInStock = 17 }, 15 | new Product { ProductID = 3, ProductName = "Aniseed Syrup", Category = "Condiments", UnitPrice = 10.0000M, UnitsInStock = 13 }, 16 | new Product { ProductID = 4, ProductName = "Chef Anton's Cajun Seasoning", Category = "Condiments", UnitPrice = 22.0000M, UnitsInStock = 53 }, 17 | new Product { ProductID = 5, ProductName = "Chef Anton's Gumbo Mix", Category = "Condiments", UnitPrice = 21.3500M, UnitsInStock = 0 }, 18 | new Product { ProductID = 6, ProductName = "Grandma's Boysenberry Spread", Category = "Condiments", UnitPrice = 25.0000M, UnitsInStock = 120 }, 19 | new Product { ProductID = 7, ProductName = "Uncle Bob's Organic Dried Pears", Category = "Produce", UnitPrice = 30.0000M, UnitsInStock = 15 }, 20 | new Product { ProductID = 8, ProductName = "Northwoods Cranberry Sauce", Category = "Condiments", UnitPrice = 40.0000M, UnitsInStock = 6 }, 21 | new Product { ProductID = 9, ProductName = "Mishi Kobe Niku", Category = "Meat/Poultry", UnitPrice = 97.0000M, UnitsInStock = 29 }, 22 | new Product { ProductID = 10, ProductName = "Ikura", Category = "Seafood", UnitPrice = 31.0000M, UnitsInStock = 31 }, 23 | new Product { ProductID = 11, ProductName = "Queso Cabrales", Category = "Dairy Products", UnitPrice = 21.0000M, UnitsInStock = 22 }, 24 | new Product { ProductID = 12, ProductName = "Queso Manchego La Pastora", Category = "Dairy Products", UnitPrice = 38.0000M, UnitsInStock = 86 }, 25 | new Product { ProductID = 13, ProductName = "Konbu", Category = "Seafood", UnitPrice = 6.0000M, UnitsInStock = 24 }, 26 | new Product { ProductID = 14, ProductName = "Tofu", Category = "Produce", UnitPrice = 23.2500M, UnitsInStock = 35 }, 27 | new Product { ProductID = 15, ProductName = "Genen Shouyu", Category = "Condiments", UnitPrice = 15.5000M, UnitsInStock = 39 }, 28 | new Product { ProductID = 16, ProductName = "Pavlova", Category = "Confections", UnitPrice = 17.4500M, UnitsInStock = 29 }, 29 | new Product { ProductID = 17, ProductName = "Alice Mutton", Category = "Meat/Poultry", UnitPrice = 39.0000M, UnitsInStock = 0 }, 30 | new Product { ProductID = 18, ProductName = "Carnarvon Tigers", Category = "Seafood", UnitPrice = 62.5000M, UnitsInStock = 42 }, 31 | new Product { ProductID = 19, ProductName = "Teatime Chocolate Biscuits", Category = "Confections", UnitPrice = 9.2000M, UnitsInStock = 25 }, 32 | new Product { ProductID = 20, ProductName = "Sir Rodney's Marmalade", Category = "Confections", UnitPrice = 81.0000M, UnitsInStock = 40 }, 33 | new Product { ProductID = 21, ProductName = "Sir Rodney's Scones", Category = "Confections", UnitPrice = 10.0000M, UnitsInStock = 3 }, 34 | new Product { ProductID = 22, ProductName = "Gustaf's Knäckebröd", Category = "Grains/Cereals", UnitPrice = 21.0000M, UnitsInStock = 104 }, 35 | new Product { ProductID = 23, ProductName = "Tunnbröd", Category = "Grains/Cereals", UnitPrice = 9.0000M, UnitsInStock = 61 }, 36 | new Product { ProductID = 24, ProductName = "Guaraná Fantástica", Category = "Beverages", UnitPrice = 4.5000M, UnitsInStock = 20 }, 37 | new Product { ProductID = 25, ProductName = "NuNuCa Nuß-Nougat-Creme", Category = "Confections", UnitPrice = 14.0000M, UnitsInStock = 76 }, 38 | new Product { ProductID = 26, ProductName = "Gumbär Gummibärchen", Category = "Confections", UnitPrice = 31.2300M, UnitsInStock = 15 }, 39 | new Product { ProductID = 27, ProductName = "Schoggi Schokolade", Category = "Confections", UnitPrice = 43.9000M, UnitsInStock = 49 }, 40 | new Product { ProductID = 28, ProductName = "Rössle Sauerkraut", Category = "Produce", UnitPrice = 45.6000M, UnitsInStock = 26 }, 41 | new Product { ProductID = 29, ProductName = "Thüringer Rostbratwurst", Category = "Meat/Poultry", UnitPrice = 123.7900M, UnitsInStock = 0 }, 42 | new Product { ProductID = 30, ProductName = "Nord-Ost Matjeshering", Category = "Seafood", UnitPrice = 25.8900M, UnitsInStock = 10 }, 43 | new Product { ProductID = 31, ProductName = "Gorgonzola Telino", Category = "Dairy Products", UnitPrice = 12.5000M, UnitsInStock = 0 }, 44 | new Product { ProductID = 32, ProductName = "Mascarpone Fabioli", Category = "Dairy Products", UnitPrice = 32.0000M, UnitsInStock = 9 }, 45 | new Product { ProductID = 33, ProductName = "Geitost", Category = "Dairy Products", UnitPrice = 2.5000M, UnitsInStock = 112 }, 46 | new Product { ProductID = 34, ProductName = "Sasquatch Ale", Category = "Beverages", UnitPrice = 14.0000M, UnitsInStock = 111 }, 47 | new Product { ProductID = 35, ProductName = "Steeleye Stout", Category = "Beverages", UnitPrice = 18.0000M, UnitsInStock = 20 }, 48 | new Product { ProductID = 36, ProductName = "Inlagd Sill", Category = "Seafood", UnitPrice = 19.0000M, UnitsInStock = 112 }, 49 | new Product { ProductID = 37, ProductName = "Gravad lax", Category = "Seafood", UnitPrice = 26.0000M, UnitsInStock = 11 }, 50 | new Product { ProductID = 38, ProductName = "Côte de Blaye", Category = "Beverages", UnitPrice = 263.5000M, UnitsInStock = 17 }, 51 | new Product { ProductID = 39, ProductName = "Chartreuse verte", Category = "Beverages", UnitPrice = 18.0000M, UnitsInStock = 69 }, 52 | new Product { ProductID = 40, ProductName = "Boston Crab Meat", Category = "Seafood", UnitPrice = 18.4000M, UnitsInStock = 123 }, 53 | new Product { ProductID = 41, ProductName = "Jack's New England Clam Chowder", Category = "Seafood", UnitPrice = 9.6500M, UnitsInStock = 85 }, 54 | new Product { ProductID = 42, ProductName = "Singaporean Hokkien Fried Mee", Category = "Grains/Cereals", UnitPrice = 14.0000M, UnitsInStock = 26 }, 55 | new Product { ProductID = 43, ProductName = "Ipoh Coffee", Category = "Beverages", UnitPrice = 46.0000M, UnitsInStock = 17 }, 56 | new Product { ProductID = 44, ProductName = "Gula Malacca", Category = "Condiments", UnitPrice = 19.4500M, UnitsInStock = 27 }, 57 | new Product { ProductID = 45, ProductName = "Rogede sild", Category = "Seafood", UnitPrice = 9.5000M, UnitsInStock = 5 }, 58 | new Product { ProductID = 46, ProductName = "Spegesild", Category = "Seafood", UnitPrice = 12.0000M, UnitsInStock = 95 }, 59 | new Product { ProductID = 47, ProductName = "Zaanse koeken", Category = "Confections", UnitPrice = 9.5000M, UnitsInStock = 36 }, 60 | new Product { ProductID = 48, ProductName = "Chocolade", Category = "Confections", UnitPrice = 12.7500M, UnitsInStock = 15 }, 61 | new Product { ProductID = 49, ProductName = "Maxilaku", Category = "Confections", UnitPrice = 20.0000M, UnitsInStock = 10 }, 62 | new Product { ProductID = 50, ProductName = "Valkoinen suklaa", Category = "Confections", UnitPrice = 16.2500M, UnitsInStock = 65 }, 63 | new Product { ProductID = 51, ProductName = "Manjimup Dried Apples", Category = "Produce", UnitPrice = 53.0000M, UnitsInStock = 20 }, 64 | new Product { ProductID = 52, ProductName = "Filo Mix", Category = "Grains/Cereals", UnitPrice = 7.0000M, UnitsInStock = 38 }, 65 | new Product { ProductID = 53, ProductName = "Perth Pasties", Category = "Meat/Poultry", UnitPrice = 32.8000M, UnitsInStock = 0 }, 66 | new Product { ProductID = 54, ProductName = "Tourtière", Category = "Meat/Poultry", UnitPrice = 7.4500M, UnitsInStock = 21 }, 67 | new Product { ProductID = 55, ProductName = "Pâté chinois", Category = "Meat/Poultry", UnitPrice = 24.0000M, UnitsInStock = 115 }, 68 | new Product { ProductID = 56, ProductName = "Gnocchi di nonna Alice", Category = "Grains/Cereals", UnitPrice = 38.0000M, UnitsInStock = 21 }, 69 | new Product { ProductID = 57, ProductName = "Ravioli Angelo", Category = "Grains/Cereals", UnitPrice = 19.5000M, UnitsInStock = 36 }, 70 | new Product { ProductID = 58, ProductName = "Escargots de Bourgogne", Category = "Seafood", UnitPrice = 13.2500M, UnitsInStock = 62 }, 71 | new Product { ProductID = 59, ProductName = "Raclette Courdavault", Category = "Dairy Products", UnitPrice = 55.0000M, UnitsInStock = 79 }, 72 | new Product { ProductID = 60, ProductName = "Camembert Pierrot", Category = "Dairy Products", UnitPrice = 34.0000M, UnitsInStock = 19 }, 73 | new Product { ProductID = 61, ProductName = "Sirop d'érable", Category = "Condiments", UnitPrice = 28.5000M, UnitsInStock = 113 }, 74 | new Product { ProductID = 62, ProductName = "Tarte au sucre", Category = "Confections", UnitPrice = 49.3000M, UnitsInStock = 17 }, 75 | new Product { ProductID = 63, ProductName = "Vegie-spread", Category = "Condiments", UnitPrice = 43.9000M, UnitsInStock = 24 }, 76 | new Product { ProductID = 64, ProductName = "Wimmers gute Semmelknödel", Category = "Grains/Cereals", UnitPrice = 33.2500M, UnitsInStock = 22 }, 77 | new Product { ProductID = 65, ProductName = "Louisiana Fiery Hot Pepper Sauce", Category = "Condiments", UnitPrice = 21.0500M, UnitsInStock = 76 }, 78 | new Product { ProductID = 66, ProductName = "Louisiana Hot Spiced Okra", Category = "Condiments", UnitPrice = 17.0000M, UnitsInStock = 4 }, 79 | new Product { ProductID = 67, ProductName = "Laughing Lumberjack Lager", Category = "Beverages", UnitPrice = 14.0000M, UnitsInStock = 52 }, 80 | new Product { ProductID = 68, ProductName = "Scottish Longbreads", Category = "Confections", UnitPrice = 12.5000M, UnitsInStock = 6 }, 81 | new Product { ProductID = 69, ProductName = "Gudbrandsdalsost", Category = "Dairy Products", UnitPrice = 36.0000M, UnitsInStock = 26 }, 82 | new Product { ProductID = 70, ProductName = "Outback Lager", Category = "Beverages", UnitPrice = 15.0000M, UnitsInStock = 15 }, 83 | new Product { ProductID = 71, ProductName = "Flotemysost", Category = "Dairy Products", UnitPrice = 21.5000M, UnitsInStock = 26 }, 84 | new Product { ProductID = 72, ProductName = "Mozzarella di Giovanni", Category = "Dairy Products", UnitPrice = 34.8000M, UnitsInStock = 14 }, 85 | new Product { ProductID = 73, ProductName = "Röd Kaviar", Category = "Seafood", UnitPrice = 15.0000M, UnitsInStock = 101 }, 86 | new Product { ProductID = 74, ProductName = "Longlife Tofu", Category = "Produce", UnitPrice = 10.0000M, UnitsInStock = 4 }, 87 | new Product { ProductID = 75, ProductName = "Rhönbräu Klosterbier", Category = "Beverages", UnitPrice = 7.7500M, UnitsInStock = 125 }, 88 | new Product { ProductID = 76, ProductName = "Lakkalikööri", Category = "Beverages", UnitPrice = 18.0000M, UnitsInStock = 57 }, 89 | new Product { ProductID = 77, ProductName = "Original Frankfurter grüne Soße", Category = "Condiments", UnitPrice = 13.0000M, UnitsInStock = 32 } 90 | }; 91 | } 92 | 93 | public static IEnumerable GetCustomerList() 94 | { 95 | return XDocument.Load("../../../Customers.xml").Root.Elements("customer") 96 | .Select(e => new Customer 97 | { 98 | CustomerID = (string)e.Element("id"), 99 | CompanyName = (string)e.Element("name"), 100 | Address = (string)e.Element("address"), 101 | City = (string)e.Element("city"), 102 | Region = (string)e.Element("region"), 103 | PostalCode = (string)e.Element("postalcode"), 104 | Country = (string)e.Element("country"), 105 | Phone = (string)e.Element("phone"), 106 | Fax = (string)e.Element("fax"), 107 | Orders = e.Elements("orders").Elements("order") 108 | .Select(o => new Order() 109 | { 110 | OrderID = (int)o.Element("id"), 111 | OrderDate = (DateTime)o.Element("orderdate"), 112 | Total = (decimal)o.Element("total") 113 | }).ToArray() 114 | }); 115 | } 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/csharp/linq-shared/TestHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Data; 3 | 4 | namespace linqshared 5 | { 6 | internal static class TestHelper 7 | { 8 | internal static DataSet CreateTestDataset() 9 | { 10 | DataSet ds = new DataSet(); 11 | 12 | // Customers Table 13 | ds.Tables.Add(CreateNumbersTable()); 14 | ds.Tables.Add(CreateLowNumbersTable()); 15 | ds.Tables.Add(CreateEmptyNumbersTable()); 16 | ds.Tables.Add(CreateProductList()); 17 | ds.Tables.Add(CreateDigitsTable()); 18 | ds.Tables.Add(CreateWordsTable()); 19 | ds.Tables.Add(CreateWords2Table()); 20 | ds.Tables.Add(CreateWords3Table()); 21 | ds.Tables.Add(CreateWords4Table()); 22 | ds.Tables.Add(CreateAnagramsTable()); 23 | ds.Tables.Add(CreateNumbersATable()); 24 | ds.Tables.Add(CreateNumbersBTable()); 25 | ds.Tables.Add(CreateFactorsOf300()); 26 | ds.Tables.Add(CreateDoublesTable()); 27 | ds.Tables.Add(CreateScoreRecordsTable()); 28 | ds.Tables.Add(CreateAttemptedWithdrawalsTable()); 29 | ds.Tables.Add(CreateEmployees1Table()); 30 | ds.Tables.Add(CreateEmployees2Table()); 31 | 32 | CreateCustomersAndOrdersTables(ds); 33 | 34 | ds.AcceptChanges(); 35 | return ds; 36 | } 37 | 38 | 39 | private static DataTable CreateNumbersTable() 40 | { 41 | 42 | int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 43 | DataTable table = new DataTable("Numbers"); 44 | table.Columns.Add("number", typeof(int)); 45 | 46 | foreach (int n in numbers) 47 | { 48 | table.Rows.Add(new object[] { n }); 49 | } 50 | 51 | return table; 52 | } 53 | 54 | private static DataTable CreateEmptyNumbersTable() 55 | { 56 | 57 | DataTable table = new DataTable("EmptyNumbers"); 58 | table.Columns.Add("number", typeof(int)); 59 | return table; 60 | } 61 | 62 | private static DataTable CreateDigitsTable() 63 | { 64 | 65 | string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 66 | DataTable table = new DataTable("Digits"); 67 | table.Columns.Add("digit", typeof(string)); 68 | 69 | foreach (string digit in digits) 70 | { 71 | table.Rows.Add(new object[] { digit }); 72 | } 73 | return table; 74 | } 75 | 76 | private static DataTable CreateWordsTable() 77 | { 78 | string[] words = { "aPPLE", "BlUeBeRrY", "cHeRry" }; 79 | DataTable table = new DataTable("Words"); 80 | table.Columns.Add("word", typeof(string)); 81 | 82 | foreach (string word in words) 83 | { 84 | table.Rows.Add(new object[] { word }); 85 | } 86 | return table; 87 | } 88 | 89 | private static DataTable CreateWords2Table() 90 | { 91 | string[] words = { "believe", "relief", "receipt", "field" }; 92 | DataTable table = new DataTable("Words2"); 93 | table.Columns.Add("word", typeof(string)); 94 | 95 | foreach (string word in words) 96 | { 97 | table.Rows.Add(new object[] { word }); 98 | } 99 | return table; 100 | } 101 | 102 | private static DataTable CreateWords3Table() 103 | { 104 | string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" }; 105 | DataTable table = new DataTable("Words3"); 106 | table.Columns.Add("word", typeof(string)); 107 | 108 | foreach (string word in words) 109 | { 110 | table.Rows.Add(new object[] { word }); 111 | } 112 | return table; 113 | } 114 | 115 | private static DataTable CreateWords4Table() 116 | { 117 | string[] words = { "blueberry", "chimpanzee", "abacus", "banana", "apple", "cheese" }; 118 | DataTable table = new DataTable("Words4"); 119 | table.Columns.Add("word", typeof(string)); 120 | 121 | foreach (string word in words) 122 | { 123 | table.Rows.Add(new object[] { word }); 124 | } 125 | return table; 126 | } 127 | 128 | private static DataTable CreateAnagramsTable() 129 | { 130 | string[] anagrams = { "from ", " salt", " earn ", " last ", " near ", " form " }; 131 | DataTable table = new DataTable("Anagrams"); 132 | table.Columns.Add("anagram", typeof(string)); 133 | 134 | foreach (string word in anagrams) 135 | { 136 | table.Rows.Add(new object[] { word }); 137 | } 138 | return table; 139 | } 140 | 141 | private static DataTable CreateScoreRecordsTable() 142 | { 143 | var scoreRecords = new[] { new {Name = "Alice", Score = 50}, 144 | new {Name = "Bob" , Score = 40}, 145 | new {Name = "Cathy", Score = 45} 146 | }; 147 | 148 | DataTable table = new DataTable("ScoreRecords"); 149 | table.Columns.Add("Name", typeof(string)); 150 | table.Columns.Add("Score", typeof(int)); 151 | 152 | foreach (var r in scoreRecords) 153 | { 154 | table.Rows.Add(new object[] { r.Name, r.Score }); 155 | } 156 | return table; 157 | } 158 | 159 | private static DataTable CreateAttemptedWithdrawalsTable() 160 | { 161 | int[] attemptedWithdrawals = { 20, 10, 40, 50, 10, 70, 30 }; 162 | 163 | DataTable table = new DataTable("AttemptedWithdrawals"); 164 | table.Columns.Add("withdrawal", typeof(int)); 165 | 166 | foreach (var r in attemptedWithdrawals) 167 | { 168 | table.Rows.Add(new object[] { r }); 169 | } 170 | return table; 171 | } 172 | 173 | private static DataTable CreateNumbersATable() 174 | { 175 | int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; 176 | DataTable table = new DataTable("NumbersA"); 177 | table.Columns.Add("number", typeof(int)); 178 | 179 | foreach (int number in numbersA) 180 | { 181 | table.Rows.Add(new object[] { number }); 182 | } 183 | return table; 184 | } 185 | 186 | private static DataTable CreateNumbersBTable() 187 | { 188 | int[] numbersB = { 1, 3, 5, 7, 8 }; 189 | DataTable table = new DataTable("NumbersB"); 190 | table.Columns.Add("number", typeof(int)); 191 | 192 | foreach (int number in numbersB) 193 | { 194 | table.Rows.Add(new object[] { number }); 195 | } 196 | return table; 197 | } 198 | 199 | private static DataTable CreateLowNumbersTable() 200 | { 201 | int[] lowNumbers = { 1, 11, 3, 19, 41, 65, 19 }; 202 | DataTable table = new DataTable("LowNumbers"); 203 | table.Columns.Add("number", typeof(int)); 204 | 205 | foreach (int number in lowNumbers) 206 | { 207 | table.Rows.Add(new object[] { number }); 208 | } 209 | return table; 210 | } 211 | 212 | private static DataTable CreateFactorsOf300() 213 | { 214 | int[] factorsOf300 = { 2, 2, 3, 5, 5 }; 215 | 216 | DataTable table = new DataTable("FactorsOf300"); 217 | table.Columns.Add("factor", typeof(int)); 218 | 219 | foreach (int factor in factorsOf300) 220 | { 221 | table.Rows.Add(new object[] { factor }); 222 | } 223 | return table; 224 | } 225 | 226 | private static DataTable CreateDoublesTable() 227 | { 228 | double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 }; 229 | 230 | DataTable table = new DataTable("Doubles"); 231 | table.Columns.Add("double", typeof(double)); 232 | 233 | foreach (double d in doubles) 234 | { 235 | table.Rows.Add(new object[] { d }); 236 | } 237 | return table; 238 | } 239 | 240 | private static DataTable CreateEmployees1Table() 241 | { 242 | 243 | DataTable table = new DataTable("Employees1"); 244 | table.Columns.Add("id", typeof(int)); 245 | table.Columns.Add("name", typeof(string)); 246 | table.Columns.Add("worklevel", typeof(int)); 247 | 248 | table.Rows.Add(new object[] { 1, "Jones", 5 }); 249 | table.Rows.Add(new object[] { 2, "Smith", 5 }); 250 | table.Rows.Add(new object[] { 2, "Smith", 5 }); 251 | table.Rows.Add(new object[] { 3, "Smith", 6 }); 252 | table.Rows.Add(new object[] { 4, "Arthur", 11 }); 253 | table.Rows.Add(new object[] { 5, "Arthur", 12 }); 254 | 255 | return table; 256 | } 257 | 258 | private static DataTable CreateEmployees2Table() 259 | { 260 | 261 | DataTable table = new DataTable("Employees2"); 262 | table.Columns.Add("id", typeof(int)); 263 | table.Columns.Add("lastname", typeof(string)); 264 | table.Columns.Add("level", typeof(int)); 265 | 266 | table.Rows.Add(new object[] { 1, "Jones", 10 }); 267 | table.Rows.Add(new object[] { 2, "Jagger", 5 }); 268 | table.Rows.Add(new object[] { 3, "Thomas", 6 }); 269 | table.Rows.Add(new object[] { 4, "Collins", 11 }); 270 | table.Rows.Add(new object[] { 4, "Collins", 12 }); 271 | table.Rows.Add(new object[] { 5, "Arthur", 12 }); 272 | 273 | return table; 274 | } 275 | 276 | private static void CreateCustomersAndOrdersTables(DataSet ds) 277 | { 278 | 279 | DataTable customers = new DataTable("Customers"); 280 | customers.Columns.Add("CustomerID", typeof(string)); 281 | customers.Columns.Add("CompanyName", typeof(string)); 282 | customers.Columns.Add("Address", typeof(string)); 283 | customers.Columns.Add("City", typeof(string)); 284 | customers.Columns.Add("Region", typeof(string)); 285 | customers.Columns.Add("PostalCode", typeof(string)); 286 | customers.Columns.Add("Country", typeof(string)); 287 | customers.Columns.Add("Phone", typeof(string)); 288 | customers.Columns.Add("Fax", typeof(string)); 289 | 290 | ds.Tables.Add(customers); 291 | 292 | DataTable orders = new DataTable("Orders"); 293 | 294 | orders.Columns.Add("OrderID", typeof(int)); 295 | orders.Columns.Add("CustomerID", typeof(string)); 296 | orders.Columns.Add("OrderDate", typeof(DateTime)); 297 | orders.Columns.Add("Total", typeof(decimal)); 298 | 299 | ds.Tables.Add(orders); 300 | 301 | DataRelation co = new DataRelation("CustomersOrders", customers.Columns["CustomerID"], orders.Columns["CustomerID"], true); 302 | ds.Relations.Add(co); 303 | 304 | var customerList = ProgramBase.GetCustomerList(); 305 | 306 | foreach (Customer cust in customerList) 307 | { 308 | customers.Rows.Add(new object[] {cust.CustomerID, cust.CompanyName, cust.Address, cust.City, cust.Region, 309 | cust.PostalCode, cust.Country, cust.Phone, cust.Fax}); 310 | foreach (Order order in cust.Orders) 311 | { 312 | orders.Rows.Add(new object[] { order.OrderID, cust.CustomerID, order.OrderDate, order.Total }); 313 | } 314 | } 315 | } 316 | 317 | private static DataTable CreateProductList() 318 | { 319 | 320 | DataTable table = new DataTable("Products"); 321 | table.Columns.Add("ProductID", typeof(int)); 322 | table.Columns.Add("ProductName", typeof(string)); 323 | table.Columns.Add("Category", typeof(string)); 324 | table.Columns.Add("UnitPrice", typeof(decimal)); 325 | table.Columns.Add("UnitsInStock", typeof(int)); 326 | 327 | var productList = new[] { 328 | new { ProductID = 1, ProductName = "Chai", Category = "Beverages", 329 | UnitPrice = 18.0000M, UnitsInStock = 39 }, 330 | new { ProductID = 2, ProductName = "Chang", Category = "Beverages", 331 | UnitPrice = 19.0000M, UnitsInStock = 17 }, 332 | new { ProductID = 3, ProductName = "Aniseed Syrup", Category = "Condiments", 333 | UnitPrice = 10.0000M, UnitsInStock = 13 }, 334 | new { ProductID = 4, ProductName = "Chef Anton's Cajun Seasoning", Category = "Condiments", 335 | UnitPrice = 22.0000M, UnitsInStock = 53 }, 336 | new { ProductID = 5, ProductName = "Chef Anton's Gumbo Mix", Category = "Condiments", 337 | UnitPrice = 21.3500M, UnitsInStock = 0 }, 338 | new { ProductID = 6, ProductName = "Grandma's Boysenberry Spread", Category = "Condiments", 339 | UnitPrice = 25.0000M, UnitsInStock = 120 }, 340 | new { ProductID = 7, ProductName = "Uncle Bob's Organic Dried Pears", Category = "Produce", 341 | UnitPrice = 30.0000M, UnitsInStock = 15 }, 342 | new { ProductID = 8, ProductName = "Northwoods Cranberry Sauce", Category = "Condiments", 343 | UnitPrice = 40.0000M, UnitsInStock = 6 }, 344 | new { ProductID = 9, ProductName = "Mishi Kobe Niku", Category = "Meat/Poultry", 345 | UnitPrice = 97.0000M, UnitsInStock = 29 }, 346 | new { ProductID = 10, ProductName = "Ikura", Category = "Seafood", 347 | UnitPrice = 31.0000M, UnitsInStock = 31 }, 348 | new { ProductID = 11, ProductName = "Queso Cabrales", Category = "Dairy Products", 349 | UnitPrice = 21.0000M, UnitsInStock = 22 }, 350 | new { ProductID = 12, ProductName = "Queso Manchego La Pastora", Category = "Dairy Products", 351 | UnitPrice = 38.0000M, UnitsInStock = 86 }, 352 | new { ProductID = 13, ProductName = "Konbu", Category = "Seafood", 353 | UnitPrice = 6.0000M, UnitsInStock = 24 }, 354 | new { ProductID = 14, ProductName = "Tofu", Category = "Produce", 355 | UnitPrice = 23.2500M, UnitsInStock = 35 }, 356 | new { ProductID = 15, ProductName = "Genen Shouyu", Category = "Condiments", 357 | UnitPrice = 15.5000M, UnitsInStock = 39 }, 358 | new { ProductID = 16, ProductName = "Pavlova", Category = "Confections", 359 | UnitPrice = 17.4500M, UnitsInStock = 29 }, 360 | new { ProductID = 17, ProductName = "Alice Mutton", Category = "Meat/Poultry", 361 | UnitPrice = 39.0000M, UnitsInStock = 0 }, 362 | new { ProductID = 18, ProductName = "Carnarvon Tigers", Category = "Seafood", 363 | UnitPrice = 62.5000M, UnitsInStock = 42 }, 364 | new { ProductID = 19, ProductName = "Teatime Chocolate Biscuits", Category = "Confections", 365 | UnitPrice = 9.2000M, UnitsInStock = 25 }, 366 | new { ProductID = 20, ProductName = "Sir Rodney's Marmalade", Category = "Confections", 367 | UnitPrice = 81.0000M, UnitsInStock = 40 }, 368 | new { ProductID = 21, ProductName = "Sir Rodney's Scones", Category = "Confections", 369 | UnitPrice = 10.0000M, UnitsInStock = 3 }, 370 | new { ProductID = 22, ProductName = "Gustaf's Knäckebröd", Category = "Grains/Cereals", 371 | UnitPrice = 21.0000M, UnitsInStock = 104 }, 372 | new { ProductID = 23, ProductName = "Tunnbröd", Category = "Grains/Cereals", 373 | UnitPrice = 9.0000M, UnitsInStock = 61 }, 374 | new { ProductID = 24, ProductName = "Guaraná Fantástica", Category = "Beverages", 375 | UnitPrice = 4.5000M, UnitsInStock = 20 }, 376 | new { ProductID = 25, ProductName = "NuNuCa Nuß-Nougat-Creme", Category = "Confections", 377 | UnitPrice = 14.0000M, UnitsInStock = 76 }, 378 | new { ProductID = 26, ProductName = "Gumbär Gummibärchen", Category = "Confections", 379 | UnitPrice = 31.2300M, UnitsInStock = 15 }, 380 | new { ProductID = 27, ProductName = "Schoggi Schokolade", Category = "Confections", 381 | UnitPrice = 43.9000M, UnitsInStock = 49 }, 382 | new { ProductID = 28, ProductName = "Rössle Sauerkraut", Category = "Produce", 383 | UnitPrice = 45.6000M, UnitsInStock = 26 }, 384 | new { ProductID = 29, ProductName = "Thüringer Rostbratwurst", Category = "Meat/Poultry", 385 | UnitPrice = 123.7900M, UnitsInStock = 0 }, 386 | new { ProductID = 30, ProductName = "Nord-Ost Matjeshering", Category = "Seafood", 387 | UnitPrice = 25.8900M, UnitsInStock = 10 }, 388 | new { ProductID = 31, ProductName = "Gorgonzola Telino", Category = "Dairy Products", 389 | UnitPrice = 12.5000M, UnitsInStock = 0 }, 390 | new { ProductID = 32, ProductName = "Mascarpone Fabioli", Category = "Dairy Products", 391 | UnitPrice = 32.0000M, UnitsInStock = 9 }, 392 | new { ProductID = 33, ProductName = "Geitost", Category = "Dairy Products", 393 | UnitPrice = 2.5000M, UnitsInStock = 112 }, 394 | new { ProductID = 34, ProductName = "Sasquatch Ale", Category = "Beverages", 395 | UnitPrice = 14.0000M, UnitsInStock = 111 }, 396 | new { ProductID = 35, ProductName = "Steeleye Stout", Category = "Beverages", 397 | UnitPrice = 18.0000M, UnitsInStock = 20 }, 398 | new { ProductID = 36, ProductName = "Inlagd Sill", Category = "Seafood", 399 | UnitPrice = 19.0000M, UnitsInStock = 112 }, 400 | new { ProductID = 37, ProductName = "Gravad lax", Category = "Seafood", 401 | UnitPrice = 26.0000M, UnitsInStock = 11 }, 402 | new { ProductID = 38, ProductName = "Côte de Blaye", Category = "Beverages", 403 | UnitPrice = 263.5000M, UnitsInStock = 17 }, 404 | new { ProductID = 39, ProductName = "Chartreuse verte", Category = "Beverages", 405 | UnitPrice = 18.0000M, UnitsInStock = 69 }, 406 | new { ProductID = 40, ProductName = "Boston Crab Meat", Category = "Seafood", 407 | UnitPrice = 18.4000M, UnitsInStock = 123 }, 408 | new { ProductID = 41, ProductName = "Jack's New England Clam Chowder", Category = "Seafood", 409 | UnitPrice = 9.6500M, UnitsInStock = 85 }, 410 | new { ProductID = 42, ProductName = "Singaporean Hokkien Fried Mee", Category = "Grains/Cereals", 411 | UnitPrice = 14.0000M, UnitsInStock = 26 }, 412 | new { ProductID = 43, ProductName = "Ipoh Coffee", Category = "Beverages", 413 | UnitPrice = 46.0000M, UnitsInStock = 17 }, 414 | new { ProductID = 44, ProductName = "Gula Malacca", Category = "Condiments", 415 | UnitPrice = 19.4500M, UnitsInStock = 27 }, 416 | new { ProductID = 45, ProductName = "Rogede sild", Category = "Seafood", 417 | UnitPrice = 9.5000M, UnitsInStock = 5 }, 418 | new { ProductID = 46, ProductName = "Spegesild", Category = "Seafood", 419 | UnitPrice = 12.0000M, UnitsInStock = 95 }, 420 | new { ProductID = 47, ProductName = "Zaanse koeken", Category = "Confections", 421 | UnitPrice = 9.5000M, UnitsInStock = 36 }, 422 | new { ProductID = 48, ProductName = "Chocolade", Category = "Confections", 423 | UnitPrice = 12.7500M, UnitsInStock = 15 }, 424 | new { ProductID = 49, ProductName = "Maxilaku", Category = "Confections", 425 | UnitPrice = 20.0000M, UnitsInStock = 10 }, 426 | new { ProductID = 50, ProductName = "Valkoinen suklaa", Category = "Confections", 427 | UnitPrice = 16.2500M, UnitsInStock = 65 }, 428 | new { ProductID = 51, ProductName = "Manjimup Dried Apples", Category = "Produce", 429 | UnitPrice = 53.0000M, UnitsInStock = 20 }, 430 | new { ProductID = 52, ProductName = "Filo Mix", Category = "Grains/Cereals", 431 | UnitPrice = 7.0000M, UnitsInStock = 38 }, 432 | new { ProductID = 53, ProductName = "Perth Pasties", Category = "Meat/Poultry", 433 | UnitPrice = 32.8000M, UnitsInStock = 0 }, 434 | new { ProductID = 54, ProductName = "Tourtière", Category = "Meat/Poultry", 435 | UnitPrice = 7.4500M, UnitsInStock = 21 }, 436 | new { ProductID = 55, ProductName = "Pâté chinois", Category = "Meat/Poultry", 437 | UnitPrice = 24.0000M, UnitsInStock = 115 }, 438 | new { ProductID = 56, ProductName = "Gnocchi di nonna Alice", Category = "Grains/Cereals", 439 | UnitPrice = 38.0000M, UnitsInStock = 21 }, 440 | new { ProductID = 57, ProductName = "Ravioli Angelo", Category = "Grains/Cereals", 441 | UnitPrice = 19.5000M, UnitsInStock = 36 }, 442 | new { ProductID = 58, ProductName = "Escargots de Bourgogne", Category = "Seafood", 443 | UnitPrice = 13.2500M, UnitsInStock = 62 }, 444 | new { ProductID = 59, ProductName = "Raclette Courdavault", Category = "Dairy Products", 445 | UnitPrice = 55.0000M, UnitsInStock = 79 }, 446 | new { ProductID = 60, ProductName = "Camembert Pierrot", Category = "Dairy Products", 447 | UnitPrice = 34.0000M, UnitsInStock = 19 }, 448 | new { ProductID = 61, ProductName = "Sirop d'érable", Category = "Condiments", 449 | UnitPrice = 28.5000M, UnitsInStock = 113 }, 450 | new { ProductID = 62, ProductName = "Tarte au sucre", Category = "Confections", 451 | UnitPrice = 49.3000M, UnitsInStock = 17 }, 452 | new { ProductID = 63, ProductName = "Vegie-spread", Category = "Condiments", 453 | UnitPrice = 43.9000M, UnitsInStock = 24 }, 454 | new { ProductID = 64, ProductName = "Wimmers gute Semmelknödel", Category = "Grains/Cereals", 455 | UnitPrice = 33.2500M, UnitsInStock = 22 }, 456 | new { ProductID = 65, ProductName = "Louisiana Fiery Hot Pepper Sauce", Category = "Condiments", 457 | UnitPrice = 21.0500M, UnitsInStock = 76 }, 458 | new { ProductID = 66, ProductName = "Louisiana Hot Spiced Okra", Category = "Condiments", 459 | UnitPrice = 17.0000M, UnitsInStock = 4 }, 460 | new { ProductID = 67, ProductName = "Laughing Lumberjack Lager", Category = "Beverages", 461 | UnitPrice = 14.0000M, UnitsInStock = 52 }, 462 | new { ProductID = 68, ProductName = "Scottish Longbreads", Category = "Confections", 463 | UnitPrice = 12.5000M, UnitsInStock = 6 }, 464 | new { ProductID = 69, ProductName = "Gudbrandsdalsost", Category = "Dairy Products", 465 | UnitPrice = 36.0000M, UnitsInStock = 26 }, 466 | new { ProductID = 70, ProductName = "Outback Lager", Category = "Beverages", 467 | UnitPrice = 15.0000M, UnitsInStock = 15 }, 468 | new { ProductID = 71, ProductName = "Flotemysost", Category = "Dairy Products", 469 | UnitPrice = 21.5000M, UnitsInStock = 26 }, 470 | new { ProductID = 72, ProductName = "Mozzarella di Giovanni", Category = "Dairy Products", 471 | UnitPrice = 34.8000M, UnitsInStock = 14 }, 472 | new { ProductID = 73, ProductName = "Röd Kaviar", Category = "Seafood", 473 | UnitPrice = 15.0000M, UnitsInStock = 101 }, 474 | new { ProductID = 74, ProductName = "Longlife Tofu", Category = "Produce", 475 | UnitPrice = 10.0000M, UnitsInStock = 4 }, 476 | new { ProductID = 75, ProductName = "Rhönbräu Klosterbier", Category = "Beverages", 477 | UnitPrice = 7.7500M, UnitsInStock = 125 }, 478 | new { ProductID = 76, ProductName = "Lakkalikööri", Category = "Beverages", 479 | UnitPrice = 18.0000M, UnitsInStock = 57 }, 480 | new { ProductID = 77, ProductName = "Original Frankfurter grüne Soße", Category = "Condiments", 481 | UnitPrice = 13.0000M, UnitsInStock = 32 } 482 | }; 483 | 484 | foreach (var x in productList) 485 | { 486 | table.Rows.Add(new object[] { x.ProductID, x.ProductName, x.Category, x.UnitPrice, x.UnitsInStock }); 487 | } 488 | 489 | return table; 490 | } 491 | } 492 | 493 | } 494 | --------------------------------------------------------------------------------