101 Linq Examples | C# Essentials: Linq For Lists – Sorting, Filtering, And Aggregating Lists Easily 상위 75개 답변

당신은 주제를 찾고 있습니까 “101 linq examples – C# Essentials: Linq for Lists – Sorting, Filtering, and Aggregating Lists Easily“? 다음 카테고리의 웹사이트 https://chewathai27.com/you 에서 귀하의 모든 질문에 답변해 드립니다: https://chewathai27.com/you/blog. 바로 아래에서 답을 찾을 수 있습니다. 작성자 IAmTimCorey 이(가) 작성한 기사에는 조회수 206,378회 및 좋아요 3,404개 개의 좋아요가 있습니다.

Table of Contents

101 linq examples 주제에 대한 동영상 보기

여기에서 이 주제에 대한 비디오를 시청하십시오. 주의 깊게 살펴보고 읽고 있는 내용에 대한 피드백을 제공하세요!

d여기에서 C# Essentials: Linq for Lists – Sorting, Filtering, and Aggregating Lists Easily – 101 linq examples 주제에 대한 세부정보를 참조하세요

Having a List for an object is a fairly common occurrence in C#. In fact, most data access systems end with having the data in a List. This video will help you see how to sort, filter, and operate on lists easily and powerfully.
You will see examples both in a Console application and in a Windows Forms application. This practical example dives right into the most important parts of Linq to get you up and running in minutes.
Get the Starter Code: https://leadmagnets.app/?Resource=Linq101
Mailing List: https://signup.iamtimcorey.com/
0:00 – Intro
0:43 – demo app walkthrough
3:56 – for each item in the list, do this – foreach loop.
5:24 – sorting the list of items by item property: OrderBy
8:42 – sort the list descending: OrderByDescending
9:29 – sort the list by more than one parameter: …ThenBy
11:18 – filter the list: Where(bool true)
15:14 – Sum of the countable property of objects in the list
16:20 – combining list methods: Where and Sum
18:29 – using Linq in applications – WinForm app walk-through: (data binding, events)
22:55 – Implementing Linq

101 linq examples 주제에 대한 자세한 내용은 여기를 참조하세요.

101 LINQ samples – Code Samples – Microsoft Docs

Learn how to use LINQ in your applications with these code samples, covering the entire range of LINQ functionality, demonstrating LINQ with …

+ 여기에 보기

Source: docs.microsoft.com

Date Published: 1/8/2022

View: 8249

LINQSamples | LINQ 101 Query and Lambda Expression …

LINQ 101 Code Samples in C#, VB and F# shown with both Lambda and Query syntax. Examples for all Operators such as Where, Select and Join based on …

+ 여기에 더 보기

Source: linqsamples.com

Date Published: 2/15/2022

View: 7166

101 LINQ Query Samples – Jon LaBelle

101 C# samples using LINQ. … [Description( “This sample uses the where clause to find all elements of an array with a value less than 5.” )].

+ 여기를 클릭

Source: jonlabelle.com

Date Published: 4/4/2021

View: 4418

erjan123/101-LINQ-Samples – GitHub

101 LINQ Samples. Contribute to erjan123/101-LINQ-Samples development by creating an account on GitHub.

+ 여기에 보기

Source: github.com

Date Published: 7/2/2021

View: 5484

Sample LINQ Queries – TutorialsTeacher

Group By. The following query returns list students group by StandardID: Example: LINQ GroupBy Query – C#. var studentsGroupByStandard = …

+ 더 읽기

Source: www.tutorialsteacher.com

Date Published: 6/27/2021

View: 5878

10 Resources for Learning LINQ – Grant Winney

Used to query and manipulate data, similar to SQL, it leads to cleaner … LINQ 101 Code Samples in C#, VB and F# shown with both Lambda and …

+ 여기에 표시

Source: grantwinney.com

Date Published: 2/23/2021

View: 5614

LINQ Query Samples – Devart

In this article you will find several examples of LINQ queries that may be useful for your application development. For the we list refer to 101 LINQ …

+ 여기를 클릭

Source: www.devart.com

Date Published: 4/30/2022

View: 3723

Has anyone done the Linq 101 samples with Lambda syntax?

I finally got around to do this job myself 🙂 All 101 samples are now converted to Lambda/Fluent syntax and published at …

+ 여기에 더 보기

Source: stackoverflow.com

Date Published: 12/30/2021

View: 1177

주제와 관련된 이미지 101 linq examples

주제와 관련된 더 많은 사진을 참조하십시오 C# Essentials: Linq for Lists – Sorting, Filtering, and Aggregating Lists Easily. 댓글에서 더 많은 관련 이미지를 보거나 필요한 경우 더 많은 관련 기사를 볼 수 있습니다.

C# Essentials: Linq for Lists - Sorting, Filtering, and Aggregating Lists Easily
C# Essentials: Linq for Lists – Sorting, Filtering, and Aggregating Lists Easily

주제에 대한 기사 평가 101 linq examples

  • Author: IAmTimCorey
  • Views: 조회수 206,378회
  • Likes: 좋아요 3,404개
  • Date Published: 2017. 1. 19.
  • Video Url link: https://www.youtube.com/watch?v=yClSNQdVD7g

What is LINQ explain with example?

Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.

What are the types of LINQ?

Types of LINQ
  • LINQ to Objects.
  • LINQ to XML(XLINQ)
  • LINQ to DataSet.
  • LINQ to SQL (DLINQ)
  • LINQ to Entities.

What are the two forms of LINQ?

LINQ comes in two syntactical flavors: The Query and the Method syntax.

What is a LINQ statement?

LINQ (Language Integrated Query) is a Microsoft programming model and methodology that essentially adds formal query capabilities into Microsoft . NET-based programming languages. LINQ offers a compact, expressive, and intelligible syntax for manipulating data.

How do you write LINQ?

There are the following two ways to write LINQ queries using the Standard Query operators, in other words Select, From, Where, Orderby, Join, Groupby and many more. Using lambda expressions. Using SQL like query expressions.

Why do we use LINQ?

Readable code: LINQ makes the code more readable so other developers can easily understand and maintain it. Standardized way of querying multiple data sources: The same LINQ syntax can be used to query multiple data sources. Compile time safety of queries: It provides type checking of objects at compile time.

What are methods in LINQ?

In LINQ, Method Syntax is used to call the extension methods of the Enumerable or Queryable static classes. It is also known as Method Extension Syntax or Fluent. However, the compiler always converts the query syntax in method syntax at compile time.

Which is better LINQ or SQL?

More importantly: when it comes to querying databases, LINQ is in most cases a significantly more productive querying language than SQL. Compared to SQL, LINQ is simpler, tidier, and higher-level. It’s rather like comparing C# to C++.

Is LINQ a database?

It is a component of version 3.5 of the . NET Framework and ably does the translation of language-integrated queries of the object model into SQL. These queries are then sent to the database for the purpose of execution. After obtaining the results from the database, LINQ to SQL again translates them to objects.

Which syntax is used in LINQ?

Most queries in the introductory Language Integrated Query (LINQ) documentation are written by using the LINQ declarative query syntax.

How do I run a SQL query in LINQ?

Add a LINQ to SQL class file. Drag and drop the respective table. Now, copy this code in the main method. We are creating an instance of sample datacontext class and then we are using this ExecuteQuery method to execute the SQL query.

How many types of LINQ are there in C#?

LINQ provides you three different ways to write a LINQ query in C# or VB.

How do you read a LINQ query?

LinQ is a ‘Language Integrated Query. ‘ LINQ provides the new way to manipulate the data, whether it is to or from the database or with an XML file or with a simple list of dynamic data. LINQ is a uniform query system in C# to retrieve the data from different sources of data and formats.

Is LINQ an ORM?

LINQ to SQL is an object-relational mapping (ORM) implementation that allows the direct 1-1 mapping of a Microsoft SQL Server database to . NET classes, and query of the resulting objects using LINQ.

Is LINQ functional programming?

LINQ technology is a form of declarative, functional programming.

How does LINQ any work?

The C# Linq Any Operator is used to check whether at least one of the elements of a data source satisfies a given condition or not. If any of the elements satisfy the given condition, then it returns true else return false. It is also used to check whether a collection contains some data or not.

What is LINQ in Visual Basic?

Language-Integrated Query (LINQ) adds query capabilities to Visual Basic and provides simple and powerful capabilities when you work with all kinds of data.

What is LINQ in Java?

LINQ is an specification, not an implementation… Lambda expressions is a part of LINQ. All projects trying to port LINQ to Java are implementations for a concrete scenario (SQL, Objects…) but does not covr the main goal of LINQ: Integrate the Language Query in the code.

What is using System LINQ in C#?

Linq Namespace. Provides classes and interfaces that support queries that use Language-Integrated Query (LINQ).

101 LINQ samples – Code Samples

101 LINQ samples

Code Sample

7 contributors

Learn how to use LINQ in your applications with these code samples, covering the entire range of LINQ functionality, demonstrating LINQ with objects. Once you’ve learned LINQ using object sequences, you can use LINQ with any supported data source. These samples leverage the interactive try.net experience in your environment.

Exploring LINQ using this tutorial

To run these samples, you’ll need to follow the instructions on the dotnet/try-samples repository to install the global dotnet try tool in your .NET environment.

Once you’ve installed the global tool, running dotnet try loads the samples into a browser. The browser pages introduce important concepts in LINQ, and you run the code interactively in your browser.

LINQ 101 Query and Lambda Expression Samples

LINQ Samples

How to use this compilation of 101 samples

On this site you will find practical 101 code samples of how to use LINQ with both Lambda and Query Expressions. All samples are written in C#, VB.Net and F#.

To the best of my knowledge, all code samples on this site work – but I can’t make any guarantees. Should you stumble upon a code snippet which doesn’t work, feel free to drop me a mail.

Use the menu on the left side to find easy-to-use code samples.

LINQ

LINQ is part of the Microsoft .NET Framework and is used to query data from specific data providers like LINQ to Objects, LINQ to Entities and LINQ to SQL.

Using LINQ for everyday tasks to query objects and whatever is loaded in memory can be very beneficial, as it may replace many trivial for-each loops and make your code easier to read, understand and maintain.

LINQ to Objects

101 LINQ Query Samples

// Copyright (C) Microsoft Corporation. All Rights Reserved. // This code released under the terms of the // Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.) // //Copyright (C) Microsoft Corporation. All rights reserved. using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows.Forms; using System.Xml.Linq; using SampleSupport; // Version Mad01 namespace SampleQueries { [Title(“101 LINQ Query Samples”)] [Prefix(“Linq”)] public class LinqSamples : SampleHarness { private readonly static string dataPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @”..\..\Data\”)); # region Sample Data Collections // Sample objects based on Northwnd data, // but not identical to it in all cases. public class Customer { public string CustomerID { get; set; } public string CompanyName { get; set; } public string Address { get; set; } public string City { get; set; } public string Region { get; set; } public string PostalCode { get; set; } public string Country { get; set; } public string Phone { get; set; } public string Fax { get; set; } public Order[] Orders { get; set; } } public class Order { public int OrderID { get; set; } public DateTime OrderDate { get; set; } public decimal Total { get; set; } } public class Product { public int ProductID { get; set; } public string ProductName { get; set; } public string Category { get; set; } public decimal UnitPrice { get; set; } public int UnitsInStock { get; set; } } public class Supplier { public string SupplierName { get; set; } public string Address { get; set; } public string City { get; set; } public string Country { get; set; } } private List productList; private List customerList; private List supplierList; #endregion [Category(“Restriction Operators”)] [Title(“Where – Simple 1”)] [Description(“This sample uses the where clause to find all elements of an array with a value less than 5.”)] public void Linq1() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var lowNums = from num in numbers where num < 5 select num; Console.WriteLine("Numbers < 5:"); foreach (var x in lowNums) { Console.WriteLine(x); } } [Category("Restriction Operators")] [Title("Where - Simple 2")] [Description("This sample uses the where clause to find all products that are out of stock.")] public void Linq2() { List products = GetProductList(); var soldOutProducts = from prod in products where prod.UnitsInStock == 0 select prod; Console.WriteLine(“Sold out products:”); foreach (var product in soldOutProducts) { Console.WriteLine(“{0} is sold out!”, product.ProductName); } } [Category(“Restriction Operators”)] [Title(“Where – Simple 3”)] [Description(“This sample uses the where clause to find all products that are in stock and ” + “cost more than 3.00 per unit.”)] public void Linq3() { List products = GetProductList(); var expensiveInStockProducts = from prod in products where prod.UnitsInStock > 0 && prod.UnitPrice > 3.00M select prod; Console.WriteLine(“In-stock products that cost more than 3.00:”); foreach (var product in expensiveInStockProducts) { Console.WriteLine(“{0} is in stock and costs more than 3.00.”, product.ProductName); } } [Category(“Restriction Operators”)] [Title(“Where – Drilldown”)] [Description(“This sample uses the where clause to find all customers in Washington ” + “and then it uses a foreach loop to iterate over the orders collection that belongs to each customer.”)] public void Linq4() { List customers = GetCustomerList(); var waCustomers = from cust in customers where cust.Region == “WA” select cust; Console.WriteLine(“Customers from Washington and their orders:”); foreach (var customer in waCustomers) { Console.WriteLine(“Customer {0}: {1}”, customer.CustomerID, customer.CompanyName); foreach (var order in customer.Orders) { Console.WriteLine(” Order {0}: {1}”, order.OrderID, order.OrderDate); } } } [Category(“Restriction Operators”)] [Title(“Where – Indexed”)] [Description(“This sample demonstrates an indexed where clause that returns digits whose name is ” + “shorter than their value.”)] public void Linq5() { string[] digits = { “zero”, “one”, “two”, “three”, “four”, “five”, “six”, “seven”, “eight”, “nine” }; var shortDigits = digits.Where((digit, index) => digit.Length < index); Console.WriteLine("Short digits:"); foreach (var d in shortDigits) { Console.WriteLine("The word {0} is shorter than its value.", d); } } [Category("Projection Operators")] [Title("Select - Simple 1")] [Description("This sample uses the select clause to produce a sequence of ints one higher than " + "those in an existing array of ints.")] public void Linq6() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var numsPlusOne = from num in numbers select num + 1; Console.WriteLine("Numbers + 1:"); foreach (var i in numsPlusOne) { Console.WriteLine(i); } } [Category("Projection Operators")] [Title("Select - Simple 2")] [Description("This sample uses the select clause to return a sequence of product names.")] public void Linq7() { List products = GetProductList(); var productNames = from prod in products select prod.ProductName; Console.WriteLine(“Product Names:”); foreach (var productName in productNames) { Console.WriteLine(productName); } } [Category(“Projection Operators”)] [Title(“Select – Transformation”)] [Description(“This sample uses the select clause to produce a sequence of strings representing ” + “the text version of a sequence of ints.”)] public void Linq8() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; string[] strings = { “zero”, “one”, “two”, “three”, “four”, “five”, “six”, “seven”, “eight”, “nine” }; var textNums = from num in numbers select strings[num]; Console.WriteLine(“Number strings:”); foreach (var str in textNums) { Console.WriteLine(str); } } [Category(“Projection Operators”)] [Title(“Select – Anonymous Types 1”)] [Description(“This sample uses the select clause to produce a sequence of the uppercase ” + “and lowercase versions of each word in the original array.”)] public void Linq9() { string[] words = { “aPPLE”, “BlUeBeRrY”, “cHeRry” }; var upperLowerWords = from word in words select new {Upper = word.ToUpper(), Lower = word.ToLower()}; foreach (var wordPair in upperLowerWords) { Console.WriteLine(“Uppercase: {0}, Lowercase: {1}”, wordPair.Upper, wordPair.Lower); } } [Category(“Projection Operators”)] [Title(“Select – Anonymous Types 2”)] [Description(“This sample uses the select clause to produce a sequence containing text ” + “representations of digits and a Boolean that specifies whether the text length is even or odd.”)] public void Linq10() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; string[] strings = { “zero”, “one”, “two”, “three”, “four”, “five”, “six”, “seven”, “eight”, “nine” }; var digitOddEvens = from num in numbers select new {Digit = strings[num], Even = (num % 2 == 0)}; foreach (var digit in digitOddEvens) { Console.WriteLine(“The digit {0} is {1}.”, digit.Digit, digit.Even ? “even” : “odd”); } } [Category(“Projection Operators”)] [Title(“Select – Anonymous Types 3”)] [Description(“This sample uses the select clause to produce a sequence containing some properties ” + “of Products, including UnitPrice which is renamed to Price ” + “in the resulting type.”)] public void Linq11() { List products = GetProductList(); var productInfos = from prod in products select new {prod.ProductName, prod.Category, Price = prod.UnitPrice}; Console.WriteLine(“Product Info:”); foreach (var productInfo in productInfos) { Console.WriteLine(“{0} is in the category {1} and costs {2} per unit.”, productInfo.ProductName, productInfo.Category, productInfo.Price); } } [Category(“Projection Operators”)] [Title(“Select – Indexed”)] [Description(“This sample uses an indexed Select clause to determine if the value of ints ” + “in an array match their position in the array.”)] public void Linq12() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var numsInPlace = numbers.Select((num, index) => new {Num = num, InPlace = (num == index)}); Console.WriteLine(“Number: In-place?”); foreach (var n in numsInPlace) { Console.WriteLine(“{0}: {1}”, n.Num, n.InPlace); } } [Category(“Projection Operators”)] [Title(“Select – Filtered”)] [Description(“This sample combines select and where to make a simple query that returns ” + “the text form of each digit less than 5.”)] public void Linq13() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; string[] digits = { “zero”, “one”, “two”, “three”, “four”, “five”, “six”, “seven”, “eight”, “nine” }; var lowNums = from num in numbers where num < 5 select digits[num]; Console.WriteLine("Numbers < 5:"); foreach (var num in lowNums) { Console.WriteLine(num); } } [Category("Projection Operators")] [Title("SelectMany - Compound from 1")] [Description("This sample uses a compound from clause to make a query that returns all pairs " + "of numbers from both arrays in which the number from numbersA is less than the number " + "from numbersB.")] public void Linq14() { int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int[] numbersB = { 1, 3, 5, 7, 8 }; var pairs = from a in numbersA from b in numbersB where a < b select new {a, b}; Console.WriteLine("Pairs where a < b:"); foreach (var pair in pairs) { Console.WriteLine("{0} is less than {1}", pair.a, pair.b); } } [Category("Projection Operators")] [Title("SelectMany - Compound from 2")] [Description("This sample uses a compound from clause to select all orders where the " + "order total is less than 500.00.")] public void Linq15() { List customers = GetCustomerList(); var orders = from cust in customers from order in cust.Orders where order.Total < 500.00M select new {cust.CustomerID, order.OrderID, order.Total}; ObjectDumper.Write(orders); } [Category("Projection Operators")] [Title("SelectMany - Compound from 3")] [Description("This sample uses a compound from clause to select all orders where the " + "order was made in 1998 or later.")] public void Linq16() { List customers = GetCustomerList(); var orders = from cust in customers from order in cust.Orders where order.OrderDate >= new DateTime(1998, 1, 1) select new {cust.CustomerID, order.OrderID, order.OrderDate}; ObjectDumper.Write(orders); } [Category(“Projection Operators”)] [Title(“SelectMany – With let”)] [Description(“This sample uses a compound from clause to select all orders where the ” + “order total is greater than 2000.00 and uses a let clause to avoid ” + “requesting the total twice.”)] public void Linq17() { List customers = GetCustomerList(); var orders = from cust in customers from order in cust.Orders let total = order.Total where total >= 2000.0M select new {cust.CustomerID, order.OrderID, total}; ObjectDumper.Write(orders); } [Category(“Projection Operators”)] [Title(“SelectMany – Compound from”)] [Description(“This sample uses compound from clauses so that filtering on customers can ” + “be done before selecting their orders. This makes the query more efficient by ” + “not selecting and then discarding orders for customers outside of Washington.”)] public void Linq18() { List customers = GetCustomerList(); DateTime cutoffDate = new DateTime(1997, 1, 1); var orders = from cust in customers where cust.Region == “WA” from order in cust.Orders where order.OrderDate >= cutoffDate select new {cust.CustomerID, order.OrderID}; ObjectDumper.Write(orders); } [Category(“Projection Operators”)] [Title(“SelectMany – Indexed”)] [Description(“This sample uses an indexed SelectMany clause to select all orders, ” + “while referring to customers by the order in which they are returned ” + “from the query.”)] public void Linq19() { List customers = GetCustomerList(); var customerOrders = customers.SelectMany( (cust, custIndex) => cust.Orders.Select(o => “Customer #” + (custIndex + 1) + ” has an order with OrderID ” + o.OrderID)); ObjectDumper.Write(customerOrders); } [Category(“Partitioning Operators”)] [Title(“Take – Simple”)] [Description(“This sample uses Take to get only the first 3 elements of ” + “the array.”)] public void Linq20() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var first3Numbers = numbers.Take(3); Console.WriteLine(“First 3 numbers:”); foreach (var n in first3Numbers) { Console.WriteLine(n); } } [Category(“Partitioning Operators”)] [Title(“Take – Nested”)] [Description(“This sample uses Take to get the first 3 orders from customers ” + “in Washington.”)] public void Linq21() { List customers = GetCustomerList(); var first3WAOrders = ( from cust in customers from order in cust.Orders where cust.Region == “WA” select new {cust.CustomerID, order.OrderID, order.OrderDate} ) .Take(3); Console.WriteLine(“First 3 orders in WA:”); foreach (var order in first3WAOrders) { ObjectDumper.Write(order); } } [Category(“Partitioning Operators”)] [Title(“Skip – Simple”)] [Description(“This sample uses Skip to get all but the first four elements of ” + “the array.”)] public void Linq22() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var allButFirst4Numbers = numbers.Skip(4); Console.WriteLine(“All but first 4 numbers:”); foreach (var n in allButFirst4Numbers) { Console.WriteLine(n); } } [Category(“Partitioning Operators”)] [Title(“Skip – Nested”)] [Description(“This sample uses Take to get all but the first 2 orders from customers ” + “in Washington.”)] public void Linq23() { List customers = GetCustomerList(); var waOrders = from cust in customers from order in cust.Orders where cust.Region == “WA” select new {cust.CustomerID, order.OrderID, order.OrderDate}; var allButFirst2Orders = waOrders.Skip(2); Console.WriteLine(“All but first 2 orders in WA:”); foreach (var order in allButFirst2Orders) { ObjectDumper.Write(order); } } [Category(“Partitioning Operators”)] [Title(“TakeWhile – Simple”)] [Description(“This sample uses TakeWhile to return elements starting from the ” + “beginning of the array until a number is read whose value is not less than 6.”)] public void Linq24() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 6); Console.WriteLine("First numbers less than 6:"); foreach (var num in firstNumbersLessThan6) { Console.WriteLine(num); } } [Category("Partitioning Operators")] [Title("TakeWhile - Indexed")] [Description("This sample uses TakeWhile to return elements starting from the " + "beginning of the array until a number is hit that is less than its position " + "in the array.")] public void Linq25() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var firstSmallNumbers = numbers.TakeWhile((n, index) => n >= index); Console.WriteLine(“First numbers not less than their position:”); foreach (var n in firstSmallNumbers) { Console.WriteLine(n); } } [Category(“Partitioning Operators”)] [Title(“SkipWhile – Simple”)] [Description(“This sample uses SkipWhile to get the elements of the array ” + “starting from the first element divisible by 3.”)] public void Linq26() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; // In the lambda expression, ‘n’ is the input parameter that identifies each // element in the collection in succession. It is is inferred to be // of type int because numbers is an int array. var allButFirst3Numbers = numbers.SkipWhile(n => n % 3 != 0); Console.WriteLine(“All elements starting from first element divisible by 3:”); foreach (var n in allButFirst3Numbers) { Console.WriteLine(n); } } [Category(“Partitioning Operators”)] [Title(“SkipWhile – Indexed”)] [Description(“This sample uses SkipWhile to get the elements of the array ” + “starting from the first element less than its position.”)] public void Linq27() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var laterNumbers = numbers.SkipWhile((n, index) => n >= index); Console.WriteLine(“All elements starting from first element less than its position:”); foreach (var n in laterNumbers) { Console.WriteLine(n); } } [Category(“Ordering Operators”)] [Title(“OrderBy – Simple 1”)] [Description(“This sample uses orderby to sort a list of words alphabetically.”)] public void Linq28() { string[] words = { “cherry”, “apple”, “blueberry” }; var sortedWords = from word in words orderby word select word; Console.WriteLine(“The sorted list of words:”); foreach (var w in sortedWords) { Console.WriteLine(w); } } [Category(“Ordering Operators”)] [Title(“OrderBy – Simple 2”)] [Description(“This sample uses orderby to sort a list of words by length.”)] public void Linq29() { string[] words = { “cherry”, “apple”, “blueberry” }; var sortedWords = from word in words orderby word.Length select word; Console.WriteLine(“The sorted list of words (by length):”); foreach (var w in sortedWords) { Console.WriteLine(w); } } [Category(“Ordering Operators”)] [Title(“OrderBy – Simple 3”)] [Description(“This sample uses orderby to sort a list of products by name. ” + “Use the \”descending\” keyword at the end of the clause to perform a reverse ordering.”)] public void Linq30() { List products = GetProductList(); var sortedProducts = from prod in products orderby prod.ProductName select prod; ObjectDumper.Write(sortedProducts); } // Custom comparer for use with ordering operators public class CaseInsensitiveComparer : IComparer { public int Compare(string x, string y) { return string.Compare(x, y, StringComparison.OrdinalIgnoreCase); } } [Category(“Ordering Operators”)] [Title(“OrderBy – Comparer”)] [Description(“This sample uses an OrderBy clause with a custom comparer to ” + “do a case-insensitive sort of the words in an array.”)] [LinkedClass(“CaseInsensitiveComparer”)] public void Linq31() { string[] words = { “aPPLE”, “AbAcUs”, “bRaNcH”, “BlUeBeRrY”, “ClOvEr”, “cHeRry”}; var sortedWords = words.OrderBy(a => a, new CaseInsensitiveComparer()); ObjectDumper.Write(sortedWords); } [Category(“Ordering Operators”)] [Title(“OrderByDescending – Simple 1”)] [Description(“This sample uses orderby and descending to sort a list of ” + “doubles from highest to lowest.”)] public void Linq32() { double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 }; var sortedDoubles = from d in doubles orderby d descending select d; Console.WriteLine(“The doubles from highest to lowest:”); foreach (var d in sortedDoubles) { Console.WriteLine(d); } } [Category(“Ordering Operators”)] [Title(“OrderByDescending – Simple 2”)] [Description(“This sample uses orderby to sort a list of products by units in stock ” + “from highest to lowest.”)] public void Linq33() { List products = GetProductList(); var sortedProducts = from prod in products orderby prod.UnitsInStock descending select prod; ObjectDumper.Write(sortedProducts); } [Category(“Ordering Operators”)] [Title(“OrderByDescending – Comparer”)] [Description(“This sample uses method syntax to call OrderByDescending because it ” + ” enables you to use a custom comparer.”)] [LinkedClass(“CaseInsensitiveComparer”)] public void Linq34() { string[] words = { “aPPLE”, “AbAcUs”, “bRaNcH”, “BlUeBeRrY”, “ClOvEr”, “cHeRry”}; var sortedWords = words.OrderByDescending(a => a, new CaseInsensitiveComparer()); ObjectDumper.Write(sortedWords); } [Category(“Ordering Operators”)] [Title(“ThenBy – Simple”)] [Description(“This sample uses a compound orderby to sort a list of digits, ” + “first by length of their name, and then alphabetically by the name itself.”)] public void Linq35() { string[] digits = { “zero”, “one”, “two”, “three”, “four”, “five”, “six”, “seven”, “eight”, “nine” }; var sortedDigits = from digit in digits orderby digit.Length, digit select digit; Console.WriteLine(“Sorted digits:”); foreach (var d in sortedDigits) { Console.WriteLine(d); } } [Category(“Ordering Operators”)] [Title(“ThenBy – Comparer”)] [Description(“The first query in this sample uses method syntax to call OrderBy and ThenBy with a custom comparer to ” + “sort first by word length and then by a case-insensitive sort of the words in an array. ” + “The second two queries show another way to perform the same task.”)] [LinkedClass(“CaseInsensitiveComparer”)] public void Linq36() { string[] words = { “aPPLE”, “AbAcUs”, “bRaNcH”, “BlUeBeRrY”, “ClOvEr”, “cHeRry”}; var sortedWords = words.OrderBy(a => a.Length) .ThenBy(a => a, new CaseInsensitiveComparer()); // Another way. TODO is this use of ThenBy correct? It seems to work on this sample array. var sortedWords2 = from word in words orderby word.Length select word; var sortedWords3 = sortedWords2.ThenBy(a => a, new CaseInsensitiveComparer()); ObjectDumper.Write(sortedWords); ObjectDumper.Write(sortedWords3); } [Category(“Ordering Operators”)] [Title(“ThenByDescending – Simple”)] [Description(“This sample uses a compound orderby to sort a list of products, ” + “first by category, and then by unit price, from highest to lowest.”)] public void Linq37() { List products = GetProductList(); var sortedProducts = from prod in products orderby prod.Category, prod.UnitPrice descending select prod; ObjectDumper.Write(sortedProducts); } [Category(“Ordering Operators”)] [Title(“ThenByDescending – Comparer”)] [Description(“This sample uses an OrderBy and a ThenBy clause with a custom comparer to ” + “sort first by word length and then by a case-insensitive descending sort ” + “of the words in an array.”)] [LinkedClass(“CaseInsensitiveComparer”)] public void Linq38() { string[] words = { “aPPLE”, “AbAcUs”, “bRaNcH”, “BlUeBeRrY”, “ClOvEr”, “cHeRry”}; var sortedWords = words.OrderBy(a => a.Length) .ThenByDescending(a => a, new CaseInsensitiveComparer()); ObjectDumper.Write(sortedWords); } [Category(“Ordering Operators”)] [Title(“Reverse”)] [Description(“This sample uses Reverse to create a list of all digits in the array whose ” + “second letter is ‘i’ that is reversed from the order in the original array.”)] public void Linq39() { string[] digits = { “zero”, “one”, “two”, “three”, “four”, “five”, “six”, “seven”, “eight”, “nine” }; var reversedIDigits = ( from digit in digits where digit[1] == ‘i’ select digit) .Reverse(); Console.WriteLine(“A backwards list of the digits with a second character of ‘i’:”); foreach (var d in reversedIDigits) { Console.WriteLine(d); } } [Category(“Grouping Operators”)] [Title(“GroupBy – Simple 1”)] [Description(“This sample uses group by to partition a list of numbers by ” + “their remainder when divided by 5.”)] public void Linq40() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var numberGroups = from num in numbers group num by num % 5 into numGroup select new { Remainder = numGroup.Key, Numbers = numGroup }; foreach (var grp in numberGroups) { Console.WriteLine(“Numbers with a remainder of {0} when divided by 5:”, grp.Remainder); foreach (var n in grp.Numbers) { Console.WriteLine(n); } } } [Category(“Grouping Operators”)] [Title(“GroupBy – Simple 2”)] [Description(“This sample uses group by to partition a list of words by ” + “their first letter.”)] public void Linq41() { string[] words = { “blueberry”, “chimpanzee”, “abacus”, “banana”, “apple”, “cheese” }; var wordGroups = from num in words group num by num[0] into grp select new { FirstLetter = grp.Key, Words = grp }; foreach (var wordgrp in wordGroups) { Console.WriteLine(“Words that start with the letter ‘{0}’:”, wordgrp.FirstLetter); foreach (var word in wordgrp.Words) { Console.WriteLine(word); } } } [Category(“Grouping Operators”)] [Title(“GroupBy – Simple 3”)] [Description(“This sample uses group by to partition a list of products by category.”)] public void Linq42() { List products = GetProductList(); var orderGroups = from prod in products group prod by prod.Category into prodGroup select new { Category = prodGroup.Key, Products = prodGroup }; ObjectDumper.Write(orderGroups, 1); } [Category(“Grouping Operators”)] [Title(“GroupBy – Nested”)] [Description(“This sample uses group by to partition a list of each customer’s orders, ” + “first by year, and then by month.”)] public void Linq43() { List customers = GetCustomerList(); var customerOrderGroups = from cust in customers select new {cust.CompanyName, YearGroups = from order in cust.Orders group order by order.OrderDate.Year into yearGroup select new {Year = yearGroup.Key, MonthGroups = from order in yearGroup group order by order.OrderDate.Month into MonthGroup select new { Month = MonthGroup.Key, Orders = MonthGroup } } }; ObjectDumper.Write(customerOrderGroups, 3); } public class AnagramEqualityComparer : IEqualityComparer { public bool Equals(string x, string y) { return getCanonicalString(x) == getCanonicalString(y); } public int GetHashCode(string obj) { return getCanonicalString(obj).GetHashCode(); } private string getCanonicalString(string word) { char[] wordChars = word.ToCharArray(); Array.Sort(wordChars); return new string(wordChars); } } [Category(“Grouping Operators”)] [Title(“GroupBy – Comparer”)] [Description(“This sample uses GroupBy with method syntax to partition trimmed elements of an array using ” + “a custom comparer that matches words that are anagrams of each other.”)] [LinkedClass(“AnagramEqualityComparer”)] public void Linq44() { string[] anagrams = {“from “, ” salt”, ” earn “, ” last “, ” near “, ” form “}; var orderGroups = anagrams.GroupBy(w => w.Trim(), new AnagramEqualityComparer()); ObjectDumper.Write(orderGroups, 1); } [Category(“Grouping Operators”)] [Title(“GroupBy – Comparer, Mapped”)] [Description(“This sample uses the GroupBy method to partition trimmed elements of an array using ” + “a custom comparer that matches words that are anagrams of each other, ” + “and then converts the results to uppercase.”)] [LinkedClass(“AnagramEqualityComparer”)] public void Linq45() { string[] anagrams = {“from “, ” salt”, ” earn “, ” last “, ” near “, ” form “}; var orderGroups = anagrams.GroupBy( w => w.Trim(), a => a.ToUpper(), new AnagramEqualityComparer() ); ObjectDumper.Write(orderGroups, 1); } [Category(“Set Operators”)] [Title(“Distinct – 1”)] [Description(“This sample uses Distinct to remove duplicate elements in a sequence of ” + “factors of 300.”)] public void Linq46() { int[] factorsOf300 = { 2, 2, 3, 5, 5 }; var uniqueFactors = factorsOf300.Distinct(); Console.WriteLine(“Prime factors of 300:”); foreach (var f in uniqueFactors) { Console.WriteLine(f); } } [Category(“Set Operators”)] [Title(“Distinct – 2”)] [Description(“This sample uses Distinct to find the unique Category names.”)] public void Linq47() { List products = GetProductList(); var categoryNames = ( from prod in products select prod.Category) .Distinct(); Console.WriteLine(“Category names:”); foreach (var n in categoryNames) { Console.WriteLine(n); } } [Category(“Set Operators”)] [Title(“Union – 1”)] [Description(“This sample uses Union to create one sequence that contains the unique values ” + “from both arrays.”)] public void Linq48() { int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int[] numbersB = { 1, 3, 5, 7, 8 }; var uniqueNumbers = numbersA.Union(numbersB); Console.WriteLine(“Unique numbers from both arrays:”); foreach (var n in uniqueNumbers) { Console.WriteLine(n); } } [Category(“Set Operators”)] [Title(“Union – 2”)] [Description(“This sample uses the Union method to create one sequence that contains the unique first letter ” + “from both product and customer names. Union is only available through method syntax.”)] public void Linq49() { List products = GetProductList(); List customers = GetCustomerList(); var productFirstChars = from prod in products select prod.ProductName[0]; var customerFirstChars = from cust in customers select cust.CompanyName[0]; var uniqueFirstChars = productFirstChars.Union(customerFirstChars); Console.WriteLine(“Unique first letters from Product names and Customer names:”); foreach (var ch in uniqueFirstChars) { Console.WriteLine(ch); } } [Category(“Set Operators”)] [Title(“Intersect – 1”)] [Description(“This sample uses Intersect to create one sequence that contains the common values ” + “shared by both arrays.”)] public void Linq50() { int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int[] numbersB = { 1, 3, 5, 7, 8 }; var commonNumbers = numbersA.Intersect(numbersB); Console.WriteLine(“Common numbers shared by both arrays:”); foreach (var n in commonNumbers) { Console.WriteLine(n); } } [Category(“Set Operators”)] [Title(“Intersect – 2”)] [Description(“This sample uses Intersect to create one sequence that contains the common first letter ” + “from both product and customer names.”)] public void Linq51() { List products = GetProductList(); List customers = GetCustomerList(); var productFirstChars = from prod in products select prod.ProductName[0]; var customerFirstChars = from cust in customers select cust.CompanyName[0]; var commonFirstChars = productFirstChars.Intersect(customerFirstChars); Console.WriteLine(“Common first letters from Product names and Customer names:”); foreach (var ch in commonFirstChars) { Console.WriteLine(ch); } } [Category(“Set Operators”)] [Title(“Except – 1”)] [Description(“This sample uses Except to create a sequence that contains the values from numbersA” + “that are not also in numbersB.”)] public void Linq52() { int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int[] numbersB = { 1, 3, 5, 7, 8 }; IEnumerable aOnlyNumbers = numbersA.Except(numbersB); Console.WriteLine(“Numbers in first array but not second array:”); foreach (var n in aOnlyNumbers) { Console.WriteLine(n); } } [Category(“Set Operators”)] [Title(“Except – 2”)] [Description(“This sample uses Except to create one sequence that contains the first letters ” + “of product names that are not also first letters of customer names.”)] public void Linq53() { List products = GetProductList(); List customers = GetCustomerList(); var productFirstChars = from prod in products select prod.ProductName[0]; var customerFirstChars = from cust in customers select cust.CompanyName[0]; var productOnlyFirstChars = productFirstChars.Except(customerFirstChars); Console.WriteLine(“First letters from Product names, but not from Customer names:”); foreach (var ch in productOnlyFirstChars) { Console.WriteLine(ch); } } [Category(“Conversion Operators”)] [Title(“ToArray”)] [Description(“This sample uses ToArray to immediately evaluate a sequence into an array.”)] public void Linq54() { double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 }; var sortedDoubles = from d in doubles orderby d descending select d; var doublesArray = sortedDoubles.ToArray(); Console.WriteLine(“Every other double from highest to lowest:”); for (int d = 0; d < doublesArray.Length; d += 2) { Console.WriteLine(doublesArray[d]); } } [Category("Conversion Operators")] [Title("ToList")] [Description("This sample uses ToList to immediately evaluate a sequence into a List.”)] public void Linq55() { string[] words = { “cherry”, “apple”, “blueberry” }; var sortedWords = from w in words orderby w select w; var wordList = sortedWords.ToList(); Console.WriteLine(“The sorted word list:”); foreach (var w in wordList) { Console.WriteLine(w); } } [Category(“Conversion Operators”)] [Title(“ToDictionary”)] [Description(“This sample uses ToDictionary to immediately evaluate a sequence and a ” + “related key expression into a dictionary.”)] public void Linq56() { var scoreRecords = new [] { new {Name = “Alice”, Score = 50}, new {Name = “Bob” , Score = 40}, new {Name = “Cathy”, Score = 45} }; var scoreRecordsDict = scoreRecords.ToDictionary(sr => sr.Name); Console.WriteLine(“Bob’s score: {0}”, scoreRecordsDict[“Bob”]); } [Category(“Conversion Operators”)] [Title(“OfType”)] [Description(“This sample uses OfType to return only the elements of the array that are of type double.”)] public void Linq57() { object[] numbers = { null, 1.0, “two”, 3, “four”, 5, “six”, 7.0 }; var doubles = numbers.OfType(); Console.WriteLine(“Numbers stored as doubles:”); foreach (var d in doubles) { Console.WriteLine(d); } } [Category(“Element Operators”)] [Title(“First – Simple”)] [Description(“This sample uses First to return the first matching element ” + “as a Product, instead of as a sequence containing a Product.”)] public void Linq58() { List products = GetProductList(); Product product12 = ( from prod in products where prod.ProductID == 12 select prod) .First(); ObjectDumper.Write(product12); } [Category(“Element Operators”)] [Title(“First – Condition”)] [Description(“This sample uses First to find the first element in the array that starts with ‘o’.”)] public void Linq59() { string[] strings = { “zero”, “one”, “two”, “three”, “four”, “five”, “six”, “seven”, “eight”, “nine” }; string startsWithO = strings.First(s => s[0] == ‘o’); Console.WriteLine(“A string starting with ‘o’: {0}”, startsWithO); } [Category(“Element Operators”)] [Title(“FirstOrDefault – Simple”)] [Description(“This sample uses FirstOrDefault 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. FirstOrDefault is useful for creating outer joins.”)] public void Linq61() { int[] numbers = {}; int firstNumOrDefault = numbers.FirstOrDefault(); Console.WriteLine(firstNumOrDefault); } [Category(“Element Operators”)] [Title(“FirstOrDefault – Condition”)] [Description(“This sample uses FirstOrDefault 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.”)] public void Linq62() { List products = GetProductList(); Product product789 = products.FirstOrDefault(p => p.ProductID == 789); Console.WriteLine(“Product 789 exists: {0}”, product789 != null); } [Category(“Element Operators”)] [Title(“ElementAt”)] [Description(“This sample uses ElementAt to retrieve the second number greater than 5 ” + “from an array.”)] public void Linq64() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; int fourthLowNum = ( from num in numbers where num > 5 select num ) .ElementAt(1); // second number is index 1 because sequences use 0-based indexing Console.WriteLine(“Second number > 5: {0}”, fourthLowNum); } [Category(“Generation Operators”)] [Title(“Range”)] [Description(“This sample uses Range to generate a sequence of numbers from 100 to 149 ” + “that is used to find which numbers in that range are odd and even.”)] public void Linq65() { var numbers = from n in Enumerable.Range(100, 50) select new {Number = n, OddEven = n % 2 == 1 ? “odd” : “even”}; foreach (var n in numbers) { Console.WriteLine(“The number {0} is {1}.”, n.Number, n.OddEven); } } [Category(“Generation Operators”)] [Title(“Repeat”)] [Description(“This sample uses Repeat to generate a sequence that contains the number 7 ten times.”)] public void Linq66() { var numbers = Enumerable.Repeat(7, 10); foreach (var n in numbers) { Console.WriteLine(n); } } [Category(“Quantifiers”)] [Title(“Any – Simple”)] [Description(“This sample uses Any to determine if any of the words in the array ” + “contain the substring ‘ei’.”)] public void Linq67() { string[] words = { “believe”, “relief”, “receipt”, “field” }; bool iAfterE = words.Any(w => w.Contains(“ei”)); //DONE fixed typo in writeline Console.WriteLine(“There is a word in the list that contains ‘ei’: {0}”, iAfterE); } [Category(“Quantifiers”)] [Title(“Any – Grouped”)] [Description(“This sample uses Any to return a grouped a list of products only for categories ” + “that have at least one product that is out of stock.”)] public void Linq69() { List products = GetProductList(); var productGroups = from prod in products group prod by prod.Category into prodGroup where prodGroup.Any(p => p.UnitsInStock == 0) select new { Category = prodGroup.Key, Products = prodGroup }; ObjectDumper.Write(productGroups, 1); } [Category(“Quantifiers”)] [Title(“All – Simple”)] [Description(“This sample uses All to determine whether an array contains ” + “only odd numbers.”)] public void Linq70() { int[] numbers = { 1, 11, 3, 19, 41, 65, 19 }; bool onlyOdd = numbers.All(n => n % 2 == 1); Console.WriteLine(“The list contains only odd numbers: {0}”, onlyOdd); } [Category(“Quantifiers”)] [Title(“All – Grouped”)] [Description(“This sample uses All to return a grouped a list of products only for categories ” + “that have all of their products in stock.”)] public void Linq72() { List products = GetProductList(); var productGroups = from prod in products group prod by prod.Category into prodGroup where prodGroup.All(p => p.UnitsInStock > 0) select new { Category = prodGroup.Key, Products = prodGroup }; ObjectDumper.Write(productGroups, 1); } [Category(“Aggregate Operators”)] [Title(“Count – Simple”)] [Description(“This sample uses Count to get the number of unique prime factors of 300.”)] public void Linq73() { int[] primeFactorsOf300 = { 2, 2, 3, 5, 5 }; int uniqueFactors = primeFactorsOf300.Distinct().Count(); Console.WriteLine(“There are {0} unique prime factors of 300.”, uniqueFactors); } [Category(“Aggregate Operators”)] [Title(“Count – Conditional”)] [Description(“This sample uses Count to get the number of odd ints in the array.”)] public void Linq74() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; int oddNumbers = numbers.Count(n => n % 2 == 1); Console.WriteLine(“There are {0} odd numbers in the list.”, oddNumbers); } [Category(“Aggregate Operators”)] [Title(“Count – Nested”)] [Description(“This sample uses Count to return a list of customers and how many orders ” + “each has.”)] public void Linq76() { List customers = GetCustomerList(); var orderCounts = from cust in customers select new {cust.CustomerID, OrderCount = cust.Orders.Count()}; ObjectDumper.Write(orderCounts); } [Category(“Aggregate Operators”)] [Title(“Count – Grouped”)] [Description(“This sample uses Count to return a list of categories and how many products ” + “each has.”)] public void Linq77() { List products = GetProductList(); var categoryCounts = from prod in products group prod by prod.Category into prodGroup select new {Category = prodGroup.Key, ProductCount = prodGroup.Count()}; ObjectDumper.Write(categoryCounts); } //DONE Changed “get the total of” to “add all” [Category(“Aggregate Operators”)] [Title(“Sum – Simple”)] [Description(“This sample uses Sum to add all the numbers in an array.”)] public void Linq78() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; double numSum = numbers.Sum(); Console.WriteLine(“The sum of the numbers is {0}.”, numSum); } [Category(“Aggregate Operators”)] [Title(“Sum – Projection”)] [Description(“This sample uses Sum to get the total number of characters of all words ” + “in the array.”)] public void Linq79() { string[] words = { “cherry”, “apple”, “blueberry” }; double totalChars = words.Sum(w => w.Length); Console.WriteLine(“There are a total of {0} characters in these words.”, totalChars); } [Category(“Aggregate Operators”)] [Title(“Sum – Grouped”)] [Description(“This sample uses Sum to get the total units in stock for each product category.”)] public void Linq80() { List products = GetProductList(); var categories = from prod in products group prod by prod.Category into prodGroup select new {Category = prodGroup.Key, TotalUnitsInStock = prodGroup.Sum(p => p.UnitsInStock)}; ObjectDumper.Write(categories); } [Category(“Aggregate Operators”)] [Title(“Min – Simple”)] [Description(“This sample uses Min to get the lowest number in an array.”)] public void Linq81() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; int minNum = numbers.Min(); Console.WriteLine(“The minimum number is {0}.”, minNum); } [Category(“Aggregate Operators”)] [Title(“Min – Projection”)] [Description(“This sample uses Min to get the length of the shortest word in an array.”)] public void Linq82() { string[] words = { “cherry”, “apple”, “blueberry” }; int shortestWord = words.Min(w => w.Length); Console.WriteLine(“The shortest word is {0} characters long.”, shortestWord); } [Category(“Aggregate Operators”)] [Title(“Min – Grouped”)] [Description(“This sample uses Min to get the cheapest price among each category’s products.”)] public void Linq83() { List products = GetProductList(); var categories = from prod in products group prod by prod.Category into prodGroup select new {Category = prodGroup.Key, CheapestPrice = prodGroup.Min(p => p.UnitPrice)}; ObjectDumper.Write(categories); } [Category(“Aggregate Operators”)] [Title(“Min – Elements”)] [Description(“This sample uses Min to get the products with the lowest price in each category.”)] public void Linq84() { List products = GetProductList(); var categories = from prod in products group prod by prod.Category into prodGroup let minPrice = prodGroup.Min(p => p.UnitPrice) select new {Category = prodGroup.Key, CheapestProducts = prodGroup.Where(p => p.UnitPrice == minPrice)}; ObjectDumper.Write(categories, 1); } [Category(“Aggregate Operators”)] [Title(“Max – Simple”)] [Description(“This sample uses Max to get the highest number in an array. Note that the method returns a single value.”)] public void Linq85() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; int maxNum = numbers.Max(); Console.WriteLine(“The maximum number is {0}.”, maxNum); } [Category(“Aggregate Operators”)] [Title(“Max – Projection”)] [Description(“This sample uses Max to get the length of the longest word in an array.”)] public void Linq86() { string[] words = { “cherry”, “apple”, “blueberry” }; int longestLength = words.Max(w => w.Length); Console.WriteLine(“The longest word is {0} characters long.”, longestLength); } [Category(“Aggregate Operators”)] [Title(“Max – Grouped”)] [Description(“This sample uses Max to get the most expensive price among each category’s products.”)] public void Linq87() { List products = GetProductList(); var categories = from prod in products group prod by prod.Category into prodGroup select new {Category = prodGroup.Key, MostExpensivePrice = prodGroup.Max(p => p.UnitPrice)}; ObjectDumper.Write(categories); } [Category(“Aggregate Operators”)] [Title(“Max – Elements”)] [Description(“This sample uses Max to get the products with the most expensive price in each category.”)] public void Linq88() { List products = GetProductList(); var categories = from prod in products group prod by prod.Category into prodGroup let maxPrice = prodGroup.Max(p => p.UnitPrice) select new {Category = prodGroup.Key, MostExpensiveProducts = prodGroup.Where(p => p.UnitPrice == maxPrice)}; ObjectDumper.Write(categories, 1); } [Category(“Aggregate Operators”)] [Title(“Average – Simple”)] [Description(“This sample uses Average to get the average of all numbers in an array.”)] public void Linq89() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; double averageNum = numbers.Average(); Console.WriteLine(“The average number is {0}.”, averageNum); } [Category(“Aggregate Operators”)] [Title(“Average – Projection”)] [Description(“This sample uses Average to get the average length of the words in the array.”)] public void Linq90() { string[] words = { “cherry”, “apple”, “blueberry” }; double averageLength = words.Average(w => w.Length); Console.WriteLine(“The average word length is {0} characters.”, averageLength); } [Category(“Aggregate Operators”)] [Title(“Average – Grouped”)] [Description(“This sample uses Average to get the average price of each category’s products.”)] public void Linq91() { List products = GetProductList(); var categories = from prod in products group prod by prod.Category into prodGroup select new {Category = prodGroup.Key, AveragePrice = prodGroup.Average(p => p.UnitPrice)}; ObjectDumper.Write(categories); } [Category(“Aggregate Operators”)] [Title(“Aggregate – Simple”)] [Description(“This sample uses Aggregate to create a running product on the array that ” + “calculates the total product of all elements.”)] public void Linq92() { double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 }; double product = doubles.Aggregate((runningProduct, nextFactor) => runningProduct * nextFactor); Console.WriteLine(“Total product of all numbers: {0}”, product); } [Category(“Aggregate Operators”)] [Title(“Aggregate – Seed”)] [Description(“This sample uses Aggregate to create a running account balance that ” + “subtracts each withdrawal from the initial balance of 100, as long as ” + “the balance never drops below 0.”)] public void Linq93() { double startBalance = 100.0; int[] attemptedWithdrawals = { 20, 10, 40, 50, 10, 70, 30 }; double endBalance = attemptedWithdrawals.Aggregate(startBalance, (balance, nextWithdrawal) => ( (nextWithdrawal <= balance) ? (balance - nextWithdrawal) : balance ) ); Console.WriteLine("Ending balance: {0}", endBalance); } [Category("Miscellaneous Operators")] [Title("Concat - 1")] [Description("This sample uses Concat to create one sequence that contains each array's " + "values, one after the other.")] public void Linq94() { int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int[] numbersB = { 1, 3, 5, 7, 8 }; var allNumbers = numbersA.Concat(numbersB); Console.WriteLine("All numbers from both arrays:"); foreach (var n in allNumbers) { Console.WriteLine(n); } } [Category("Miscellaneous Operators")] [Title("Concat - 2")] [Description("This sample uses Concat to create one sequence that contains the names of " + "all customers and products, including any duplicates.")] public void Linq95() { List customers = GetCustomerList(); List products = GetProductList(); var customerNames = from cust in customers select cust.CompanyName; var productNames = from prod in products select prod.ProductName; var allNames = customerNames.Concat(productNames); Console.WriteLine(“Customer and product names:”); foreach (var n in allNames) { Console.WriteLine(n); } } [Category(“Miscellaneous Operators”)] [Title(“EqualAll – 1”)] [Description(“This sample uses SequenceEquals to see if two sequences match on all elements ” + “in the same order.”)] public void Linq96() { var wordsA = new string[] { “cherry”, “apple”, “blueberry” }; var wordsB = new string[] { “cherry”, “apple”, “blueberry” }; bool match = wordsA.SequenceEqual(wordsB); Console.WriteLine(“The sequences match: {0}”, match); } [Category(“Miscellaneous Operators”)] [Title(“EqualAll – 2”)] [Description(“This sample uses SequenceEqual to see if two sequences match on all elements ” + “in the same order.”)] public void Linq97() { var wordsA = new string[] { “cherry”, “apple”, “blueberry” }; var wordsB = new string[] { “apple”, “blueberry”, “cherry” }; bool match = wordsA.SequenceEqual(wordsB); Console.WriteLine(“The sequences match: {0}”, match); } [Category(“Query Execution”)] [Title(“Deferred Execution”)] [Description(“The following sample shows how query execution is deferred until the query is ” + “enumerated at a foreach statement.”)] public void Linq99() { // Queries are not executed until you enumerate over them. int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; int i = 0; var simpleQuery = from num in numbers select ++i; // The local variable ‘i’ is not incremented // until the query is executed in the foreach loop. Console.WriteLine(“The current value of i is {0}”, i); //i is still zero foreach (var item in simpleQuery) { Console.WriteLine(“v = {0}, i = {1}”, item, i); // now i is incremented } } [Category(“Query Execution”)] [Title(“Immediate Execution”)] [Description(“The following sample shows how queries can be executed immediately, and their results ” + ” stored in memory, with methods such as ToList.”)] public void Linq100() { // Methods like ToList(), Max(), and Count() cause the query to be // executed immediately. int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; int i = 0; var immediateQuery = ( from num in numbers select ++i ) .ToList(); Console.WriteLine(“The current value of i is {0}”, i); //i has been incremented foreach (var item in immediateQuery) { Console.WriteLine(“v = {0}, i = {1}”, item, i); } } [Category(“Query Execution”)] [Title(“Query Reuse”)] [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.”)] public void Linq101() { // Deferred execution lets us define a query once // and then reuse it later in various ways. int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var lowNumbers = from num in numbers where num <= 3 select num; Console.WriteLine("First run numbers <= 3:"); foreach (int n in lowNumbers) { Console.WriteLine(n); } // Query the original query. var lowEvenNumbers = from num in lowNumbers where num % 2 == 0 select num; Console.WriteLine("Run lowEvenNumbers query:"); foreach (int n in lowEvenNumbers) { Console.WriteLine(n); } // Modify the source data. for (int i = 0; i < 10; i++) { numbers[i] = -numbers[i]; } // During this second run, the same query object, // lowNumbers, will be iterating over the new state // of numbers[], producing different results: Console.WriteLine("Second run numbers <= 3:"); foreach (int n in lowNumbers) { Console.WriteLine(n); } } [Category("Join Operators")] [Title("Inner Join")] [Description("This sample shows how to perform a simple inner equijoin of two sequences to " + "to produce a flat result set that consists of each element in suppliers that has a matching element " + "in customers.")] public void Linq102() { List customers = GetCustomerList(); List suppliers = GetSupplierList(); var custSupJoin = from sup in suppliers join cust in customers on sup.Country equals cust.Country select new { Country = sup.Country, SupplierName = sup.SupplierName, CustomerName = cust.CompanyName }; foreach (var item in custSupJoin) { Console.WriteLine(“Country = {0}, Supplier = {1}, Customer = {2}”, item.Country, item.SupplierName, item.CustomerName); } } [Category(“Join Operators”)] [Title(“Group Join”)] [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.”)] public void Linq103() { List customers = GetCustomerList(); List suppliers = GetSupplierList(); var custSupQuery = from sup in suppliers join cust in customers on sup.Country equals cust.Country into cs select new { Key = sup.Country, Items = cs }; foreach (var item in custSupQuery) { Console.WriteLine(item.Key + “:”); foreach (var element in item.Items) { Console.WriteLine(” ” + element.CompanyName); } } } [Category(“Join Operators”)] [Title(“Cross Join with Group Join”)] [Description(“The group join operator is more general than join, as this slightly more verbose ” + “version of the cross join sample shows.”)] public void Linq104() { string[] categories = new string[]{ “Beverages”, “Condiments”, “Vegetables”, “Dairy Products”, “Seafood” }; List products = GetProductList(); var prodByCategory = from cat in categories join prod in products on cat equals prod.Category into ps from p in ps select new { Category = cat, p.ProductName }; foreach (var item in prodByCategory) { Console.WriteLine(item.ProductName + “: ” + item.Category); } } [Category(“Join Operators”)] [Title(“Left Outer Join”)] [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.”)] public void Linq105() { List customers = GetCustomerList(); List suppliers = GetSupplierList(); var supplierCusts = from sup in suppliers join cust in customers on sup.Country equals cust.Country into cs from c in cs.DefaultIfEmpty() // DefaultIfEmpty preserves left-hand elements that have no matches on the right side orderby sup.SupplierName select new { Country = sup.Country, CompanyName = c == null ? “(No customers)” : c.CompanyName, SupplierName = sup.SupplierName}; foreach (var item in supplierCusts) { Console.WriteLine(“{0} ({1}): {2}”, item.SupplierName, item.Country, item.CompanyName); } } [Category(“Join Operators”)] [Title(“Left Outer Join No. 2”)] [Description(“For each customer in the table of customers, this query returns all the suppliers ” + “from that same country, or else a string indicating that no suppliers from that country were found.”)] public void Linq106() { List customers = GetCustomerList(); List suppliers = GetSupplierList(); var custSuppliers = from cust in customers join sup in suppliers on cust.Country equals sup.Country into ss from s in ss.DefaultIfEmpty() orderby cust.CompanyName select new { Country = cust.Country, CompanyName = cust.CompanyName, SupplierName = s == null ? “(No suppliers)” : s.SupplierName }; foreach (var item in custSuppliers) { Console.WriteLine(“{0} ({1}): {2}”, item.CompanyName, item.Country, item.SupplierName); } } [Category(“Join Operators”)] [Title(“Left Outer Join with Composite Key”)] [Description(“For each supplier in the table of suppliers, this query returns all the customers ” + “from the same city and country, or else a string indicating that no customers from that city/country were found. ” + “Note the use of anonymous types to encapsulate the multiple key values.”)] public void Linq107() { List customers = GetCustomerList(); List suppliers = GetSupplierList(); var supplierCusts = from sup in suppliers join cust in customers on new { sup.City, sup.Country } equals new { cust.City, cust.Country } into cs from c in cs.DefaultIfEmpty() //Remove DefaultIfEmpty method call to make this an inner join orderby sup.SupplierName select new { Country = sup.Country, City = sup.City, SupplierName = sup.SupplierName, CompanyName = c == null ? “(No customers)” : c.CompanyName }; foreach (var item in supplierCusts) { Console.WriteLine(“{0} ({1}, {2}): {3}”, item.SupplierName, item.City, item.Country, item.CompanyName); } } [Category(“* Sample Data *”)] [Title(“CustomerList / ProductList / Supplier List”)] [Description(“This method displays the sample data used by the queries above. You can also see ” + “the method below that constructs the lists. ProductList and supplierList are built by using ” + “collection initializers and CustomerList uses XLinq to read its values ” + “into memory from an XML document.”)] [LinkedMethod(“GetProductList”)] [LinkedMethod(“GetSupplierList”)] [LinkedMethod(“GetCustomerList”)] [LinkedMethod(“createLists”)] public void Linq115() { ObjectDumper.Write(GetCustomerList(), 1); Console.WriteLine(); ObjectDumper.Write(GetProductList()); } public List GetProductList() { if (productList == null) createLists(); return productList; } public List GetSupplierList() { if (supplierList == null) createLists(); return supplierList; } public List GetCustomerList() { if (customerList == null) createLists(); return customerList; } private void createLists() { // Product data created in-memory using collection initializer: productList = new List { new Product { ProductID = 1, ProductName = “Chai”, Category = “Beverages”, UnitPrice = 18.0000M, UnitsInStock = 39 }, new Product { ProductID = 2, ProductName = “Chang”, Category = “Beverages”, UnitPrice = 19.0000M, UnitsInStock = 17 }, new Product { ProductID = 3, ProductName = “Aniseed Syrup”, Category = “Condiments”, UnitPrice = 10.0000M, UnitsInStock = 13 }, new Product { ProductID = 4, ProductName = “Chef Anton’s Cajun Seasoning”, Category = “Condiments”, UnitPrice = 22.0000M, UnitsInStock = 53 }, new Product { ProductID = 5, ProductName = “Chef Anton’s Gumbo Mix”, Category = “Condiments”, UnitPrice = 21.3500M, UnitsInStock = 0 }, new Product { ProductID = 6, ProductName = “Grandma’s Boysenberry Spread”, Category = “Condiments”, UnitPrice = 25.0000M, UnitsInStock = 120 }, new Product { ProductID = 7, ProductName = “Uncle Bob’s Organic Dried Pears”, Category = “Produce”, UnitPrice = 30.0000M, UnitsInStock = 15 }, new Product { ProductID = 8, ProductName = “Northwoods Cranberry Sauce”, Category = “Condiments”, UnitPrice = 40.0000M, UnitsInStock = 6 }, new Product { ProductID = 9, ProductName = “Mishi Kobe Niku”, Category = “Meat/Poultry”, UnitPrice = 97.0000M, UnitsInStock = 29 }, new Product { ProductID = 10, ProductName = “Ikura”, Category = “Seafood”, UnitPrice = 31.0000M, UnitsInStock = 31 }, new Product { ProductID = 11, ProductName = “Queso Cabrales”, Category = “Dairy Products”, UnitPrice = 21.0000M, UnitsInStock = 22 }, new Product { ProductID = 12, ProductName = “Queso Manchego La Pastora”, Category = “Dairy Products”, UnitPrice = 38.0000M, UnitsInStock = 86 }, new Product { ProductID = 13, ProductName = “Konbu”, Category = “Seafood”, UnitPrice = 6.0000M, UnitsInStock = 24 }, new Product { ProductID = 14, ProductName = “Tofu”, Category = “Produce”, UnitPrice = 23.2500M, UnitsInStock = 35 }, new Product { ProductID = 15, ProductName = “Genen Shouyu”, Category = “Condiments”, UnitPrice = 15.5000M, UnitsInStock = 39 }, new Product { ProductID = 16, ProductName = “Pavlova”, Category = “Confections”, UnitPrice = 17.4500M, UnitsInStock = 29 }, new Product { ProductID = 17, ProductName = “Alice Mutton”, Category = “Meat/Poultry”, UnitPrice = 39.0000M, UnitsInStock = 0 }, new Product { ProductID = 18, ProductName = “Carnarvon Tigers”, Category = “Seafood”, UnitPrice = 62.5000M, UnitsInStock = 42 }, new Product { ProductID = 19, ProductName = “Teatime Chocolate Biscuits”, Category = “Confections”, UnitPrice = 9.2000M, UnitsInStock = 25 }, new Product { ProductID = 20, ProductName = “Sir Rodney’s Marmalade”, Category = “Confections”, UnitPrice = 81.0000M, UnitsInStock = 40 }, new Product { ProductID = 21, ProductName = “Sir Rodney’s Scones”, Category = “Confections”, UnitPrice = 10.0000M, UnitsInStock = 3 }, new Product { ProductID = 22, ProductName = “Gustaf’s Knäckebröd”, Category = “Grains/Cereals”, UnitPrice = 21.0000M, UnitsInStock = 104 }, new Product { ProductID = 23, ProductName = “Tunnbröd”, Category = “Grains/Cereals”, UnitPrice = 9.0000M, UnitsInStock = 61 }, new Product { ProductID = 24, ProductName = “Guaraná Fantástica”, Category = “Beverages”, UnitPrice = 4.5000M, UnitsInStock = 20 }, new Product { ProductID = 25, ProductName = “NuNuCa Nuß-Nougat-Creme”, Category = “Confections”, UnitPrice = 14.0000M, UnitsInStock = 76 }, new Product { ProductID = 26, ProductName = “Gumbär Gummibärchen”, Category = “Confections”, UnitPrice = 31.2300M, UnitsInStock = 15 }, new Product { ProductID = 27, ProductName = “Schoggi Schokolade”, Category = “Confections”, UnitPrice = 43.9000M, UnitsInStock = 49 }, new Product { ProductID = 28, ProductName = “Rössle Sauerkraut”, Category = “Produce”, UnitPrice = 45.6000M, UnitsInStock = 26 }, new Product { ProductID = 29, ProductName = “Thüringer Rostbratwurst”, Category = “Meat/Poultry”, UnitPrice = 123.7900M, UnitsInStock = 0 }, new Product { ProductID = 30, ProductName = “Nord-Ost Matjeshering”, Category = “Seafood”, UnitPrice = 25.8900M, UnitsInStock = 10 }, new Product { ProductID = 31, ProductName = “Gorgonzola Telino”, Category = “Dairy Products”, UnitPrice = 12.5000M, UnitsInStock = 0 }, new Product { ProductID = 32, ProductName = “Mascarpone Fabioli”, Category = “Dairy Products”, UnitPrice = 32.0000M, UnitsInStock = 9 }, new Product { ProductID = 33, ProductName = “Geitost”, Category = “Dairy Products”, UnitPrice = 2.5000M, UnitsInStock = 112 }, new Product { ProductID = 34, ProductName = “Sasquatch Ale”, Category = “Beverages”, UnitPrice = 14.0000M, UnitsInStock = 111 }, new Product { ProductID = 35, ProductName = “Steeleye Stout”, Category = “Beverages”, UnitPrice = 18.0000M, UnitsInStock = 20 }, new Product { ProductID = 36, ProductName = “Inlagd Sill”, Category = “Seafood”, UnitPrice = 19.0000M, UnitsInStock = 112 }, new Product { ProductID = 37, ProductName = “Gravad lax”, Category = “Seafood”, UnitPrice = 26.0000M, UnitsInStock = 11 }, new Product { ProductID = 38, ProductName = “Côte de Blaye”, Category = “Beverages”, UnitPrice = 263.5000M, UnitsInStock = 17 }, new Product { ProductID = 39, ProductName = “Chartreuse verte”, Category = “Beverages”, UnitPrice = 18.0000M, UnitsInStock = 69 }, new Product { ProductID = 40, ProductName = “Boston Crab Meat”, Category = “Seafood”, UnitPrice = 18.4000M, UnitsInStock = 123 }, new Product { ProductID = 41, ProductName = “Jack’s New England Clam Chowder”, Category = “Seafood”, UnitPrice = 9.6500M, UnitsInStock = 85 }, new Product { ProductID = 42, ProductName = “Singaporean Hokkien Fried Mee”, Category = “Grains/Cereals”, UnitPrice = 14.0000M, UnitsInStock = 26 }, new Product { ProductID = 43, ProductName = “Ipoh Coffee”, Category = “Beverages”, UnitPrice = 46.0000M, UnitsInStock = 17 }, new Product { ProductID = 44, ProductName = “Gula Malacca”, Category = “Condiments”, UnitPrice = 19.4500M, UnitsInStock = 27 }, new Product { ProductID = 45, ProductName = “Rogede sild”, Category = “Seafood”, UnitPrice = 9.5000M, UnitsInStock = 5 }, new Product { ProductID = 46, ProductName = “Spegesild”, Category = “Seafood”, UnitPrice = 12.0000M, UnitsInStock = 95 }, new Product { ProductID = 47, ProductName = “Zaanse koeken”, Category = “Confections”, UnitPrice = 9.5000M, UnitsInStock = 36 }, new Product { ProductID = 48, ProductName = “Chocolade”, Category = “Confections”, UnitPrice = 12.7500M, UnitsInStock = 15 }, new Product { ProductID = 49, ProductName = “Maxilaku”, Category = “Confections”, UnitPrice = 20.0000M, UnitsInStock = 10 }, new Product { ProductID = 50, ProductName = “Valkoinen suklaa”, Category = “Confections”, UnitPrice = 16.2500M, UnitsInStock = 65 }, new Product { ProductID = 51, ProductName = “Manjimup Dried Apples”, Category = “Produce”, UnitPrice = 53.0000M, UnitsInStock = 20 }, new Product { ProductID = 52, ProductName = “Filo Mix”, Category = “Grains/Cereals”, UnitPrice = 7.0000M, UnitsInStock = 38 }, new Product { ProductID = 53, ProductName = “Perth Pasties”, Category = “Meat/Poultry”, UnitPrice = 32.8000M, UnitsInStock = 0 }, new Product { ProductID = 54, ProductName = “Tourtière”, Category = “Meat/Poultry”, UnitPrice = 7.4500M, UnitsInStock = 21 }, new Product { ProductID = 55, ProductName = “Pâté chinois”, Category = “Meat/Poultry”, UnitPrice = 24.0000M, UnitsInStock = 115 }, new Product { ProductID = 56, ProductName = “Gnocchi di nonna Alice”, Category = “Grains/Cereals”, UnitPrice = 38.0000M, UnitsInStock = 21 }, new Product { ProductID = 57, ProductName = “Ravioli Angelo”, Category = “Grains/Cereals”, UnitPrice = 19.5000M, UnitsInStock = 36 }, new Product { ProductID = 58, ProductName = “Escargots de Bourgogne”, Category = “Seafood”, UnitPrice = 13.2500M, UnitsInStock = 62 }, new Product { ProductID = 59, ProductName = “Raclette Courdavault”, Category = “Dairy Products”, UnitPrice = 55.0000M, UnitsInStock = 79 }, new Product { ProductID = 60, ProductName = “Camembert Pierrot”, Category = “Dairy Products”, UnitPrice = 34.0000M, UnitsInStock = 19 }, new Product { ProductID = 61, ProductName = “Sirop d’érable”, Category = “Condiments”, UnitPrice = 28.5000M, UnitsInStock = 113 }, new Product { ProductID = 62, ProductName = “Tarte au sucre”, Category = “Confections”, UnitPrice = 49.3000M, UnitsInStock = 17 }, new Product { ProductID = 63, ProductName = “Vegie-spread”, Category = “Condiments”, UnitPrice = 43.9000M, UnitsInStock = 24 }, new Product { ProductID = 64, ProductName = “Wimmers gute Semmelknödel”, Category = “Grains/Cereals”, UnitPrice = 33.2500M, UnitsInStock = 22 }, new Product { ProductID = 65, ProductName = “Louisiana Fiery Hot Pepper Sauce”, Category = “Condiments”, UnitPrice = 21.0500M, UnitsInStock = 76 }, new Product { ProductID = 66, ProductName = “Louisiana Hot Spiced Okra”, Category = “Condiments”, UnitPrice = 17.0000M, UnitsInStock = 4 }, new Product { ProductID = 67, ProductName = “Laughing Lumberjack Lager”, Category = “Beverages”, UnitPrice = 14.0000M, UnitsInStock = 52 }, new Product { ProductID = 68, ProductName = “Scottish Longbreads”, Category = “Confections”, UnitPrice = 12.5000M, UnitsInStock = 6 }, new Product { ProductID = 69, ProductName = “Gudbrandsdalsost”, Category = “Dairy Products”, UnitPrice = 36.0000M, UnitsInStock = 26 }, new Product { ProductID = 70, ProductName = “Outback Lager”, Category = “Beverages”, UnitPrice = 15.0000M, UnitsInStock = 15 }, new Product { ProductID = 71, ProductName = “Flotemysost”, Category = “Dairy Products”, UnitPrice = 21.5000M, UnitsInStock = 26 }, new Product { ProductID = 72, ProductName = “Mozzarella di Giovanni”, Category = “Dairy Products”, UnitPrice = 34.8000M, UnitsInStock = 14 }, new Product { ProductID = 73, ProductName = “Röd Kaviar”, Category = “Seafood”, UnitPrice = 15.0000M, UnitsInStock = 101 }, new Product { ProductID = 74, ProductName = “Longlife Tofu”, Category = “Produce”, UnitPrice = 10.0000M, UnitsInStock = 4 }, new Product { ProductID = 75, ProductName = “Rhönbräu Klosterbier”, Category = “Beverages”, UnitPrice = 7.7500M, UnitsInStock = 125 }, new Product { ProductID = 76, ProductName = “Lakkalikööri”, Category = “Beverages”, UnitPrice = 18.0000M, UnitsInStock = 57 }, new Product { ProductID = 77, ProductName = “Original Frankfurter grüne Soße”, Category = “Condiments”, UnitPrice = 13.0000M, UnitsInStock = 32 } }; supplierList = new List(){ new Supplier {SupplierName = “Exotic Liquids”, Address = “49 Gilbert St.”, City = “London”, Country = “UK”}, new Supplier {SupplierName = “New Orleans Cajun Delights”, Address = “P.O. Box 78934”, City = “New Orleans”, Country = “USA”}, new Supplier {SupplierName = “Grandma Kelly’s Homestead”, Address = “707 Oxford Rd.”, City = “Ann Arbor”, Country = “USA”}, new Supplier {SupplierName = “Tokyo Traders”, Address = “9-8 Sekimai Musashino-shi”, City = “Tokyo”, Country = “Japan”}, new Supplier {SupplierName = “Cooperativa de Quesos ‘Las Cabras'”, Address = “Calle del Rosal 4”, City = “Oviedo”, Country = “Spain”}, new Supplier {SupplierName = “Mayumi’s”, Address = “92 Setsuko Chuo-ku”, City = “Osaka”, Country = “Japan”}, new Supplier {SupplierName = “Pavlova, Ltd.”, Address = “74 Rose St. Moonie Ponds”, City = “Melbourne”, Country = “Australia”}, new Supplier {SupplierName = “Specialty Biscuits, Ltd.”, Address = “29 King’s Way”, City = “Manchester”, Country = “UK”}, new Supplier {SupplierName = “PB Knäckebröd AB”, Address = “Kaloadagatan 13”, City = “Göteborg”, Country = “Sweden”}, new Supplier {SupplierName = “Refrescos Americanas LTDA”, Address = “Av. das Americanas 12.890”, City = “Sao Paulo”, Country = “Brazil”}, new Supplier {SupplierName = “Heli Süßwaren GmbH & Co. KG”, Address = “Tiergartenstraße 5”, City = “Berlin”, Country = “Germany”}, new Supplier {SupplierName = “Plutzer Lebensmittelgroßmärkte AG”, Address = “Bogenallee 51”, City = “Frankfurt”, Country = “Germany”}, new Supplier {SupplierName = “Nord-Ost-Fisch Handelsgesellschaft mbH”, Address = “Frahmredder 112a”, City = “Cuxhaven”, Country = “Germany”}, new Supplier {SupplierName = “Formaggi Fortini s.r.l.”, Address = “Viale Dante, 75”, City = “Ravenna”, Country = “Italy”}, new Supplier {SupplierName = “Norske Meierier”, Address = “Hatlevegen 5”, City = “Sandvika”, Country = “Norway”}, new Supplier {SupplierName = “Bigfoot Breweries”, Address = “3400 – 8th Avenue Suite 210”, City = “Bend”, Country = “USA”}, new Supplier {SupplierName = “Svensk Sjöföda AB”, Address = “Brovallavägen 231”, City = “Stockholm”, Country = “Sweden”}, new Supplier {SupplierName = “Aux joyeux ecclésiastiques”, Address = “203, Rue des Francs-Bourgeois”, City = “Paris”, Country = “France”}, new Supplier {SupplierName = “New England Seafood Cannery”, Address = “Order Processing Dept. 2100 Paul Revere Blvd.”, City = “Boston”, Country = “USA”}, new Supplier {SupplierName = “Leka Trading”, Address = “471 Serangoon Loop, Suite #402”, City = “Singapore”, Country = “Singapore”}, new Supplier {SupplierName = “Lyngbysild”, Address = “Lyngbysild Fiskebakken 10”, City = “Lyngby”, Country = “Denmark”}, new Supplier {SupplierName = “Zaanse Snoepfabriek”, Address = “Verkoop Rijnweg 22”, City = “Zaandam”, Country = “Netherlands”}, new Supplier {SupplierName = “Karkki Oy”, Address = “Valtakatu 12”, City = “Lappeenranta”, Country = “Finland”}, new Supplier {SupplierName = “G’day, Mate”, Address = “170 Prince Edward Parade Hunter’s Hill”, City = “Sydney”, Country = “Australia”}, new Supplier {SupplierName = “Ma Maison”, Address = “2960 Rue St. Laurent”, City = “Montréal”, Country = “Canada”}, new Supplier {SupplierName = “Pasta Buttini s.r.l.”, Address = “Via dei Gelsomini, 153”, City = “Salerno”, Country = “Italy”}, new Supplier {SupplierName = “Escargots Nouveaux”, Address = “22, rue H. Voiron”, City = “Montceau”, Country = “France”}, new Supplier {SupplierName = “Gai pâturage”, Address = “Bat. B 3, rue des Alpes”, City = “Annecy”, Country = “France”}, new Supplier {SupplierName = “Forêts d’érables”, Address = “148 rue Chasseur”, City = “Ste-Hyacinthe”, Country = “Canada”}, }; // Customer/order data read into memory from XML file using XLinq: string customerListPath = Path.GetFullPath(Path.Combine(dataPath, “customers.xml”)); customerList = ( from e in XDocument.Load(customerListPath). Root.Elements(“customer”) select new Customer { CustomerID = (string)e.Element(“id”), CompanyName = (string)e.Element(“name”), Address = (string)e.Element(“address”), City = (string)e.Element(“city”), Region = (string)e.Element(“region”), PostalCode = (string)e.Element(“postalcode”), Country = (string)e.Element(“country”), Phone = (string)e.Element(“phone”), Fax = (string)e.Element(“fax”), Orders = ( from o in e.Elements(“orders”).Elements(“order”) select new Order { OrderID = (int)o.Element(“id”), OrderDate = (DateTime)o.Element(“orderdate”), Total = (decimal)o.Element(“total”) } ) .ToArray() } ) .ToList(); } } } // ———————– // Copyright (C) Microsoft Corporation. All Rights Reserved. // This code released under the terms of the // Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.) // //Copyright (C) Microsoft Corporation. All rights reserved. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using SampleSupport; using System.Xml; using System.Text.RegularExpressions; using System.Globalization; using System.IO; using System.Windows.Forms; namespace SampleQueries { [Title(“101+ Linq To Xml Query Samples”)] [Prefix(“XLinq”)] public class LinqToXmlSamples : SampleHarness { public string dataPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @”..\..\Data\”)); [Category(“Load”)] [Title(“Load document from file”)] [Description(“Load an XML document from a file”)] public void XLinq1() { XDocument doc = XDocument.Load(dataPath + “bib.xml”); Console.WriteLine(doc); } [Category(“Load”)] [Title(“Load document from string”)] [Description(“Load document from string”)] public void XLinq2() { string xml = “” + “XClarity Samples” + “Matt” + ““; XDocument doc = XDocument.Parse(xml); Console.WriteLine(doc); } //load an XML document from XmlReader [Category(“Load”)] [Title(“Load document from XmlReader”)] [Description(“Load an XML document from XmlReader”)] public void XLinq3() { XmlReader reader = XmlReader.Create(dataPath + “bib.xml”); XDocument doc = XDocument.Load(reader); Console.WriteLine(doc); } [Category(“Load”)] [Title(“Element from XmlReader – 1”)] [Description(“Construct XElement from XmlReader positioned on an element”)] public void XLinq4() { XmlReader reader = XmlReader.Create(dataPath + “nw_customers.xml”); reader.Read();//move to root reader.Read(); // move to fist customer XElement c = (XElement)XNode.ReadFrom(reader); Console.WriteLine(c); } [Category(“Load”)] [Title(“Element from XmlReader – 2”)] [Description(“Read XElement content from XmlReader”)] public void XLinq5() { XmlReader reader = XmlReader.Create(dataPath + “config.xml”); //the file has comments and whitespace at the start reader.Read(); reader.Read(); XElement config = new XElement(“appSettings”, “This content will be replaced”); config.RemoveAll(); while (!reader.EOF) config.Add(XNode.ReadFrom(reader)); Console.WriteLine(config); } [Category(“Construction”)] [Title(“Construct an XElement from string”)] [Description(“Construct an XElement from string”)] public void XLinq6() { string xml = “” + “Motor” + “Cable” + ““; XElement po = XElement.Parse(xml); Console.WriteLine(po); } [Category(“Construction”)] [Title(“Add XML declaration to a document”)] [Description(“Add XML declaration to a document”)] public void XLinq7() { XDocument doc = new XDocument(new XDeclaration(“1.0”, “UTF-16”, “Yes”), new XElement(“foo”)); StringWriter sw = new StringWriter(); doc.Save(sw); Console.WriteLine(sw); } [Category(“Construction”)] [Title(“Computed element name”)] [Description(“Computed element name”)] public void XLinq8() { XDocument customers = XDocument.Load(dataPath + “nw_customers.xml”); string name = (string)customers.Elements(“Root”) .Elements(“Customers”) .First() .Attribute(“CustomerID”); XElement result = new XElement(name, “Element with a computed name”); Console.WriteLine(result); } [Category(“Construction”)] [Title(“Document creation”)] [Description(“Create a simple config file”)] public void XLinq9() { XDocument myDocument = new XDocument( new XElement(“configuration”, new XElement(“system.web”, new XElement(“membership”, new XElement(“providers”, new XElement(“add”, new XAttribute(“name”, “WebAdminMembershipProvider”), new XAttribute(“type”, “System.Web.Administration.WebAdminMembershipProvider”)))), new XElement(“httpModules”, new XElement(“add”, new XAttribute(“name”, “WebAdminModule”), new XAttribute(“type”, “System.Web.Administration.WebAdminModule”))), new XElement(“authentication”, new XAttribute(“mode”, “Windows”)), new XElement(“authorization”, new XElement(“deny”, new XAttribute(“users”, “?”))), new XElement(“identity”, new XAttribute(“impersonate”, “true”)), new XElement(“trust”, new XAttribute(“level”, “full”)), new XElement(“pages”, new XAttribute(“validationRequest”, “true”))))); Console.WriteLine(myDocument); } // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // [Category(“Construction”)] [Title(“Create an XmlSchema”)] [Description(“Create an XmlSchema”)] public void XLinq10() { XNamespace XSD = “http://www.w3.org/2001/XMLSchema”; XNamespace SQL = “urn:schemas-microsoft-com:mapping-schema”; XElement result = new XElement(XSD + “schema”, new XAttribute(XNamespace.Xmlns + “xsd”, “http://www.w3.org/2001/XMLSchema”), new XAttribute(XNamespace.Xmlns + “sql”, “urn:schemas-microsoft-com:mapping-schema”), new XElement(XSD + “element”, new XAttribute(“name”, “root”), new XAttribute(SQL + “is-constant”, “1”), new XElement(XSD + “complexType”, new XElement(XSD + “sequence”, new XElement(XSD + “element”, new XAttribute(“name”, “Customers”), new XAttribute(“minOccurs”, “100”), new XAttribute(“maxOccurs”, “unbounded”), new XElement(XSD + “complexType”, new XElement(XSD + “sequence”, new XElement(XSD + “element”, new XAttribute(“name”, “CompanyName”), new XAttribute(“type”, “xsd:string”)), new XElement(XSD + “element”, new XAttribute(“name”, “ContactName”), new XAttribute(“type”, “xsd:string”)), new XElement(XSD + “element”, new XAttribute(“name”, “ContactTitle”), new XAttribute(“type”, “xsd:string”)), new XElement(XSD + “element”, new XAttribute(“name”, “Phone”), new XAttribute(“type”, “xsd:string”)), new XElement(XSD + “element”, new XAttribute(“name”, “Fax”), new XAttribute(“type”, “xsd:string”)), new XElement(XSD + “element”, new XAttribute(“ref”, “FullAddress”), new XAttribute(“maxOccurs”, “3”)), new XElement(XSD + “element”, new XAttribute(“name”, “Date”), new XAttribute(“type”, “xsd:date”))), new XElement(XSD + “attribute”, new XAttribute(“name”, “CustomerID”), new XAttribute(“type”, “xsd:integer”))))))), new XElement(XSD + “element”, new XAttribute(“name”, “FullAddress”), new XAttribute(SQL + “relation”, “Customers”), new XAttribute(SQL + “relationship”, “CustAdd”), new XAttribute(SQL + “key-fields”, “CustomerID”), new XElement(XSD + “complexType”, new XElement(XSD + “sequence”, new XElement(XSD + “element”, new XAttribute(“name”, “Address”), new XAttribute(“type”, “xsd:string”)), new XElement(XSD + “element”, new XAttribute(“name”, “City”), new XAttribute(“type”, “xsd:string”)), new XElement(XSD + “element”, new XAttribute(“name”, “Region”), new XAttribute(“type”, “xsd:string”)), new XElement(XSD + “element”, new XAttribute(“name”, “PostalCode”), new XAttribute(“type”, “xsd:string”)), new XElement(XSD + “element”, new XAttribute(“name”, “Country”), new XAttribute(“type”, “xsd:string”)))))); Console.WriteLine(result); } [Category(“Construction”)] [Title(“Construct a PI”)] [Description(“Create an XML document with an XSLT PI”)] public void XLinq11() { XDocument result = new XDocument( new XProcessingInstruction(“xml-stylesheet”, “type=’text/xsl’ href=’diff.xsl'”), new XElement(“foo”)); Console.WriteLine(result); } [Category(“Construction”)] [Title(“XML comment construction”)] [Description(“XML comment construction”)] public void XLinq12() { XDocument result = new XDocument( new XComment(“My phone book”), new XElement(“phoneBook”, new XComment(“My friends”), new XElement(“Contact”, new XAttribute(“name”, “Ralph”), new XElement(“homephone”, “425-234-4567”), new XElement(“cellphone”, “206-345-75656”)), new XElement(“Contact”, new XAttribute(“name”, “Dave”), new XElement(“homephone”, “516-756-9454”), new XElement(“cellphone”, “516-762-1546”)), new XComment(“My family”), new XElement(“Contact”, new XAttribute(“name”, “Julia”), new XElement(“homephone”, “425-578-1053”), new XElement(“cellphone”, “”)), new XComment(“My team”), new XElement(“Contact”, new XAttribute(“name”, “Robert”), new XElement(“homephone”, “345-565-1653”), new XElement(“cellphone”, “321-456-2567”)))); Console.WriteLine(result); } [Category(“Construction”)] [Title(“Create a CData section”)] [Description(“Create a CData section”)] public void XLinq13() { XElement e = new XElement(“Dump”, new XCData(“this is some xml“), new XText(“some other text”)); Console.WriteLine(“Element Value: {0}”, e.Value); Console.WriteLine(“Text nodes collapsed!: {0}”, e.Nodes().First()); Console.WriteLine(“CData preserved on serialization: {0}”, e); } [Category(“Construction”)] [Title(“Create a sequence of nodes”)] [Description(“Create a sequence of customer elements”)] public void XLinq14() { var cSequence = new[] { new XElement(“customer”, new XAttribute(“id”,”x”),”new customer”), new XElement(“customer”, new XAttribute(“id”,”y”),”new customer”), new XElement(“customer”, new XAttribute(“id”,”z”),”new customer”)}; foreach (var c in cSequence) Console.WriteLine(c); } [Category(“Write”)] [Title(“Write an XElement to XmlWriter”)] [Description(“Write an XElement to XmlWriter using the WriteTo method”)] public void XLinq15() { XElement po1 = new XElement(“PurchaseOrder”, new XElement(“Item”, “Motor”, new XAttribute(“price”, “100”))); XElement po2 = new XElement(“PurchaseOrder”, new XElement(“Item”, “Cable”, new XAttribute(“price”, “10”))); XElement po3 = new XElement(“PurchaseOrder”, new XElement(“Item”, “Switch”, new XAttribute(“price”, “10”))); StringWriter sw = new StringWriter(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; XmlWriter w = XmlWriter.Create(sw, settings); w.WriteStartElement(“PurchaseOrders”); po1.WriteTo(w); po2.WriteTo(w); po3.WriteTo(w); w.WriteEndElement(); w.Close(); Console.WriteLine(sw.ToString()); } [Category(“Write”)] [Title(“Write the content of an XDocument to XmlWriter”)] [Description(“Write the content of XDocument to XmlWriter using the WriteTo method”)] public void XLinq16() { XDocument doc1 = new XDocument( new XElement(“PurchaseOrders”, new XElement(“PurchaseOrder”, new XElement(“Item”, “Motor”, new XAttribute(“price”, “100”))), new XElement(“PurchaseOrder”, new XElement(“Item”, “Cable”, new XAttribute(“price”, “10”))))); XDocument doc2 = new XDocument( new XElement(“PurchaseOrders”, new XElement(“PurchaseOrder”, new XElement(“Item”, “Switch”, new XAttribute(“price”, “10”))))); StringWriter sw = new StringWriter(); XmlWriter w = XmlWriter.Create(sw); w.WriteStartDocument(); w.WriteStartElement(“AllPurchaseOrders”); doc1.Root.WriteTo(w); doc2.Root.WriteTo(w); w.WriteEndElement(); w.WriteEndDocument(); w.Close(); Console.WriteLine(sw.ToString()); } [Category(“Write”)] [Title(“Save XDocument”)] [Description(“Save XDocument using XmlWriter/TextWriter/File”)] public void XLinq17() { XDocument doc = new XDocument( new XElement(“PurchaseOrders”, new XElement(“PurchaseOrder”, new XElement(“Item”, “Motor”, new XAttribute(“price”, “100”))), new XElement(“PurchaseOrder”, new XElement(“Item”, “Switch”, new XAttribute(“price”, “10”))), new XElement(“PurchaseOrder”, new XElement(“Item”, “Cable”, new XAttribute(“price”, “10”))))); StringWriter sw = new StringWriter(); //save to XmlWriter XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; XmlWriter w = XmlWriter.Create(sw, settings); doc.Save(w); w.Close(); Console.WriteLine(sw.ToString()); //save to file doc.Save(“out.xml”); } [Category(“Query”)] [Title(“Query for child elements”)] [Description(“Select all the customers in the xml document”)] public void XLinq18() { XDocument doc = XDocument.Load(dataPath + “nw_customers.xml”); foreach (XElement result in doc.Elements(“Root”) .Elements(“Customers”)) Console.WriteLine(result); } [Category(“Query”)] [Title(“Query for all child elements”)] [Description(“Select all the child elements of the first customer”)] public void XLinq19() { XDocument doc = XDocument.Load(dataPath + “nw_customers.xml”); var query = doc.Element(“Root”) .Element(“Customers”) .Elements(); foreach (XElement result in query) Console.WriteLine(result); } [Category(“Query”)] [Title(“Query for first child element – 1”)] [Description(“Select the first customer in the document”)] public void XLinq20() { XDocument doc = XDocument.Load(dataPath + “nw_customers.xml”); var result = doc.Element(“Root”) .Element(“Customers”); Console.WriteLine(result); } [Category(“Query”)] [Title(“Query for first child element – 2”)] [Description(“Query for one child element on a sequence of elements”)] public void XLinq21() { XDocument doc = XDocument.Load(dataPath + “nw_customers.xml”); var result = doc.Elements() .Elements(“Customers”) .First() .Element(“CompanyName”); Console.WriteLine(result); } [Category(“Query”)] [Title(“Query for attributes”)] [Description(“Selects all the CustomerIDs in the xml document”)] public void XLinq22() { XDocument doc = XDocument.Load(dataPath + “nw_customers.xml”); var query = doc.Element(“Root”) .Elements(“Customers”) .Attributes(“CustomerID”); foreach (XAttribute result in query) Console.WriteLine(result.Name + ” = ” + result.Value); } [Category(“Query”)] [Title(“Cast an attribute to a number”)] [Description(“Find orders with price > 100”)] public void XLinq23() { string xml = “” + “Motor” + “Cable” + “Modem” + “Monitor” + “Mouse” + ““; XElement order = XElement.Parse(xml); var query = from i in order.Elements(“item”) where (int)i.Attribute(“price”) > 100 select i; foreach (var result in query) Console.WriteLine(“Expensive Item {0} costs {1}”, (string)result, (string)result.Attribute(“price”)); } [Category(“Query”)] [Title(“Get the root element of a document”)] [Description(“Get the root element of a document”)] public void XLinq24() { XElement root = XDocument.Load(dataPath + “config.xml”) .Root; Console.WriteLine(“Name of root element is {0}”, root.Name); } [Category(“Query”)] [Title(“Filter query results using where”)] [Description(“Filter query results using where”)] public void XLinq25() { XDocument doc = XDocument.Load(dataPath + “nw_customers.xml”); var query = from c in doc.Element(“Root”) .Elements(“Customers”) where c.Element(“FullAddress”) .Element(“Country”) .Value == “Germany” select c; foreach (XElement result in query) Console.WriteLine(result); } [Category(“Query”)] [Title(“Select all descendants of an element”)] [Description(“Select all ContactName elements in the document”)] public void XLinq26() { XDocument doc = XDocument.Load(dataPath + “nw_customers.xml”); var query = doc.Descendants(“ContactName”); foreach (XElement result in query) Console.WriteLine(result); } [Category(“Query”)] [Title(“Select all descendants of a given type”)] [Description(“Select all text in the document”)] public void XLinq27() { XDocument doc = XDocument.Load(dataPath + “nw_customers.xml”); var query = doc.DescendantNodes().OfType().Select(t => t.Value); foreach (string result in query) Console.WriteLine(result); } [Category(“Query”)] [Title(“Select all ancestors”)] [Description(“Check if two nodes belong to the same document”)] public void XLinq28() { XDocument doc = XDocument.Load(dataPath + “nw_customers.xml”); XElement element1 = doc.Element(“Root”); XElement element2 = doc.Descendants(“Customers”) .ElementAt(3); var query = from a in element1.AncestorsAndSelf() from b in element2.AncestorsAndSelf() where a == b select a; Console.WriteLine(query.Any()); } [Category(“Query”)] [Title(“Query for parent”)] [Description(“Query for parent of an Element”)] public void XLinq29() { XElement item = new XElement(“item-01”, “Computer”); XElement order = new XElement(“order”, item); XElement p = item.Parent; Console.WriteLine(p.Name); } [Category(“Query”)] [Title(“Join over two sequences”)] [Description(“Add customer company info to orders of the first customer”)] public void XLinq30() { XDocument customers = XDocument.Load(dataPath + “nw_customers.xml”); XDocument orders = XDocument.Load(dataPath + “nw_orders.xml”); var query = from customer in customers.Descendants(“Customers”).Take(1) join order in orders.Descendants(“Orders”) on (string)customer.Attribute(“CustomerID”) equals (string)order.Element(“CustomerID”) select new XElement(“Order”, order.Nodes(), customer.Element(“CompanyName”)); foreach (var result in query) Console.WriteLine(result); } [Category(“Query”)] [Title(“Query content of a type”)] [Description(“Query content of a given type of an existing element”)] public void XLinq31() { XElement elem = new XElement(“customer”, new XElement(“name”, “jack”), “some text”, new XComment(“new customer”), new XAttribute(“id”, “abc”)); //string content foreach (XText s in elem.Nodes().OfType()) Console.WriteLine(“String content: {0}”, s); //element content foreach (XElement e in elem.Elements()) Console.WriteLine(“Element content: {0}”, e); //comment content foreach (XComment c in elem.Nodes().OfType()) Console.WriteLine(“Comment content: {0}”, c); } [Category(“Query”)] [Title(“Query using XStreamingElement”)] [Description(“Query for all Swedish customer orders and Swedish orders whose freight is > 250”)] [LinkedMethod(“GetSwedishFreightProfile”)] [LinkedMethod(“GetSwedishCustomerOrders”)] [LinkedMethod(“AddNewOrder”)] public void XLinq32() { XDocument customers = XDocument.Load(dataPath + “nw_customers.xml”); XDocument orders = XDocument.Load(dataPath + “nw_orders.xml”); XStreamingElement summary = new XStreamingElement(“Summary”, new XAttribute(“Country”, “Sweden”), new XStreamingElement(“SwedishCustomerOrders”, GetSwedishCustomerOrders(customers, orders)), new XStreamingElement(“Orders”, GetSwedishFreightProfile(orders))); Console.WriteLine(summary); //DML operation, which adds a new order for customer BERGS freight > 250 AddNewOrder(orders); Console.WriteLine(“****XStreaming Output after DML reflects new order added!!****”); Console.WriteLine(summary); } static void AddNewOrder(XDocument orders) { string order = @” BERGS 301 Sweden “; XElement newOrder = XElement.Parse(order); orders.Root.Add(newOrder); } private static IEnumerable GetSwedishFreightProfile(XDocument orders) { return from order in orders.Descendants(“Orders”) where (string)order.Element(“ShipInfo”).Element(“ShipCountry”) == “Sweden” && (float)order.Element(“ShipInfo”).Element(“Freight”) > 250 select new XElement(“Order”, new XAttribute(“Freight”, (string)order.Element(“ShipInfo”).Element(“Freight”))); } private static IEnumerable GetSwedishCustomerOrders(XDocument customers, XDocument orders) { return from customer in customers.Descendants(“Customers”) where (string)customer.Element(“FullAddress”).Element(“Country”) == “Sweden” select new XElement(“Customer”, new XAttribute(“Name”, (string)customer.Element(“CompanyName”)), new XAttribute(“OrderCount”, (from order in orders.Descendants(“Orders”) where (string)order.Element(“CustomerID”) == (string)customer.Attribute(“CustomerID”) select order).Count())); } [Category(“Query”)] [Title(“Positional predicate”)] [Description(“Query the 3rd customer in the document”)] public void XLinq33() { XDocument doc = XDocument.Load(dataPath + “nw_customers.xml”); var c = doc.Descendants(“Customers”) .ElementAt(2); Console.WriteLine(c); } [Category(“Query”)] [Title(“Union two sequences of nodes”)] [Description(“Union books authored by two authors: Serge and Peter”)] public void XLinq34() { XDocument doc = XDocument.Load(dataPath + “bib.xml”); var b1 = doc.Descendants(“book”) .Where(b => b.Elements(“author”) .Elements(“first”) .Any(f => (string)f == “Serge”)); var b2 = doc.Descendants(“book”) .Where(b => b.Elements(“author”) .Elements(“first”) .Any(f => (string)f == “Peter”)); var books = b1.Union(b2); foreach (var b in books) Console.WriteLine(b); } [Category(“Query”)] [Title(“Intersect two sequences of nodes”)] [Description(“Intersect books that are common for both authors”)] public void XLinq35() { XDocument doc = XDocument.Load(dataPath + “bib.xml”); var b1 = doc.Descendants(“book”) .Where(b => b.Elements(“author”) .Elements(“first”) .Any(f => (string)f == “Serge”)); var b2 = doc.Descendants(“book”) .Where(b => b.Elements(“author”) .Elements(“first”) .Any(f => (string)f == “Peter”)); var books = b1.Intersect(b2); foreach (var b in books) Console.WriteLine(b); } [Category(“Query”)] [Title(“All nodes in sequence 1 except the nodes in sequence 2”)] [Description(“Find books that are authored by Peter and did not have Serge as co-author”)] public void XLinq36() { XDocument doc = XDocument.Load(dataPath + “bib.xml”); var b1 = doc.Descendants(“book”) .Where(b => b.Elements(“author”) .Elements(“first”) .Any(f => (string)f == “Serge”)); var b2 = doc.Descendants(“book”) .Where(b => b.Elements(“author”) .Elements(“first”) .Any(f => (string)f == “Peter”)); var books = b2.Except(b1); foreach (var b in books) Console.WriteLine(b); } [Category(“Query”)] [Title(“Reverse the order of nodes in a sequence”)] [Description(“Display the path to a node”)] [LinkedMethod(“PrintPath”)] public void XLinq37() { XDocument doc = XDocument.Load(dataPath + “bib.xml”); XElement e = doc.Descendants(“last”) .First(); PrintPath(e); } static void PrintPath(XElement e) { var nodes = e.AncestorsAndSelf() .Reverse(); foreach (var n in nodes) Console.Write(n.Name + (n == e ? “” : “->”)); } [Category(“Query”)] [Title(“Equality of sequences”)] [Description(“Check if 2 sequences of nodes are equal. ” + “Did Serge and peter co-author all of their the books?”)] public void XLinq38() { XDocument doc = XDocument.Load(dataPath + “bib.xml”); var b1 = doc.Descendants(“book”) .Where(b => b.Elements(“author”) .Elements(“first”) .Any(f => (string)f == “Serge”)); var b2 = doc.Descendants(“book”) .Where(b => b.Elements(“author”) .Elements(“first”) .Any(f => (string)f == “Peter”)); bool result = b2.SequenceEqual(b1); Console.WriteLine(result); } [Category(“Query”)] [Title(“TakeWhile operator”)] [Description(“List books until total price is less that $150”)] public void XLinq39() { XDocument doc = XDocument.Load(dataPath + “bib.xml”); double sum = 0; var query = doc.Descendants(“book”) .TakeWhile(c => (sum += (double)c.Element(“price”)) <= 150); foreach (var result in query) Console.WriteLine(result); } [Category("Query")] [Title("Create a list of numbers")] [Description("Create 5 new customers with different IDs")] public void XLinq40() { var query = from i in Enumerable.Range(1, 5) select new XElement("Customer", new XAttribute("id", i), "New customer"); foreach (var result in query) Console.WriteLine(result); } [Category("Query")] [Title("Repeat operator")] [Description("Initialize new orders with items")] public void XLinq41() { var orders = new XElement[] { new XElement("order", new XAttribute("itemCount",5)), new XElement("order", new XAttribute("itemCount",2)), new XElement("order", new XAttribute("itemCount",3))}; //add empty items foreach (var order in orders) order.Add(Enumerable.Repeat(new XElement("item", "New item"), (int)order.Attribute("itemCount"))); foreach (var o in orders) Console.WriteLine(o); } [Category("Query")] [Title("Any operator")] [Description("Check if there are any customers in Argentina")] public void XLinq42() { XDocument doc = XDocument.Load(dataPath + "nw_Customers.xml"); if (doc.Descendants("Country").Any(c => (string)c == “Argentina”)) Console.WriteLine(“There are cusotmers in Argentina”); else Console.WriteLine(“There are no cusotmers in Argentina”); } [Category(“Query”)] [Title(“All operator”)] [Description(“Check if all books have at least one author”)] public void XLinq43() { XDocument doc = XDocument.Load(dataPath + “bib.xml”); bool query = doc.Descendants(“book”) .All(b => b.Descendants(“author”).Count() > 0); if (query) Console.WriteLine(“All books have authors”); else Console.WriteLine(“Some books dont have authors”); } [Category(“Query”)] [Title(“Count operartor”)] [Description(“Find the number of orders for a customer”)] public void XLinq44() { XDocument doc = XDocument.Load(dataPath + “nw_Orders.xml”); var query = doc.Descendants(“Orders”) .Where(o => (string)o.Element(“CustomerID”) == “VINET”); Console.WriteLine(“Customer has {0} orders”, query.Count()); } [Category(“Query”)] [Title(“Aggregate operator”)] [Description(“Find tax on an order”)] [LinkedMethod(“Tax”)] public void XLinq45() { string xml = “” + “Motor” + “Cable” + ““; XElement order = XElement.Parse(xml); double tax = order.Elements(“item”) .Aggregate((double)0, Tax); Console.WriteLine(“The total tax on the order @10% is ${0}”, tax); } static double Tax(double seed, XElement item) { return seed + (double)item.Attribute(“price”) * 0.1; } [Category(“Query”)] [Title(“Distinct operator”)] [Description(“Find all the countries where there is a customer”)] public void XLinq46() { XDocument doc = XDocument.Load(dataPath + “nw_Customers.xml”); var countries = doc.Descendants(“Country”) .Select(c => (string)c) .Distinct() .OrderBy(c => c); foreach (var c in countries) Console.WriteLine(c); } [Category(“Query”)] [Title(“Concat operator”)] [Description(“List all books by Serge and Peter with co-authored books repeated”)] public void XLinq47() { XDocument doc = XDocument.Load(dataPath + “bib.xml”); var b1 = doc.Descendants(“book”) .Where(b => b.Elements(“author”) .Elements(“first”) .Any(f => (string)f == “Serge”)); var b2 = doc.Descendants(“book”) .Where(b => b.Elements(“author”) .Elements(“first”) .Any(f => (string)f == “Peter”)); var books = b1.Concat(b2); foreach (var b in books) Console.WriteLine(b); } [Category(“Query”)] [Title(“Take operator”)] [Description(“Query the first two customers”)] public void XLinq48() { XDocument doc = XDocument.Load(dataPath + “nw_Customers.xml”); var customers = doc.Descendants(“Customers”).Take(2); foreach (var c in customers) Console.WriteLine(c); } [Category(“Query”)] [Title(“Skip operator”)] [Description(“Skip the first 3 books”)] public void XLinq49() { XDocument doc = XDocument.Load(dataPath + “bib.xml”); var books = doc.Descendants(“book”).Skip(3); foreach (var b in books) Console.WriteLine(b); } [Category(“Query”)] [Title(“Skip nodes based on a condition”)] [Description(“Print items that dont fit in budget”)] public void XLinq50() { string xml = “” + “Motor” + “Cable” + “Modem” + “Monitor” + “Mouse” + ““; XElement order = XElement.Parse(xml); int sum = 0; var items = order.Descendants(“item”) .SkipWhile(i => (sum += (int)i.Attribute(“price”)) < 300); foreach (var i in items) Console.WriteLine("{0} does not fit in you budget", (string)i); } [Category("Query")] [Title("SelectMany operator")] [Description("Get all books authored by Serge and Peter")] [LinkedMethod("GetBooks")] public void XLinq51() { string[] authors = { "Serge", "Peter" }; var books = authors.SelectMany(a => GetBooks(a)); foreach (var b in books) Console.WriteLine(b); } public IEnumerable GetBooks(string author) { XDocument doc = XDocument.Load(dataPath + “bib.xml”); var query = doc.Descendants(“book”) .Where(b => b.Elements(“author”) .Elements(“first”) .Any(f => (string)f == author)); return query; } [Category(“Query”)] [Title(“Container document”)] [Description(“Find the container document of an element”)] public void XLinq52() { XElement c = XDocument.Load(dataPath + “bib.xml”).Descendants(“book”).First(); XDocument container = c.Document; Console.WriteLine(container); } [Category(“Grouping”)] [Title(“Group orders by customer”)] [Description(“Group orders by customer”)] public void XLinq53() { XDocument doc = XDocument.Load(dataPath + “nw_orders.xml”); var query = from o in doc.Descendants(“Orders”) group o by (string)o.Element(“CustomerID”) into oGroup select oGroup; foreach (var result in query.SelectMany(g => g)) Console.WriteLine(result); } [Category(“Grouping”)] [Title(“Group customers by country and city”)] [Description(“Create a directory of customers grouped by country and city”)] public void XLinq54() { XDocument customers = XDocument.Load(dataPath + “nw_customers.xml”); XElement directory = new XElement(“directory”, from customer in customers.Descendants(“Customers”) from country in customer.Elements(“FullAddress”).Elements(“Country”) group customer by (string)country into countryGroup let country = countryGroup.Key select new XElement(“Country”, new XAttribute(“name”, country), new XAttribute(“numberOfCustomers”, countryGroup.Count()), from customer in countryGroup from city in customer.Descendants(“City”) group customer by (string)city into cityGroup let city = cityGroup.Key select new XElement(“City”, new XAttribute(“name”, city), new XAttribute(“numberOfCustomers”, cityGroup.Count()), cityGroup.Elements(“ContactName”)))); Console.WriteLine(directory); } [Category(“Grouping”)] [Title(“Group orders by customer”)] [Description(“Group orders by customer and return all customers (+ orders) for cust

erjan123/101-LINQ-Samples: 101 LINQ Samples

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Language Integrated Query (LINQ) in C#

Table of contents

Language Integrated Query (LINQ)

Article

02/18/2022

3 minutes to read

10 contributors

In this article

Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support. Furthermore, you have to learn a different query language for each type of data source: SQL databases, XML documents, various Web services, and so on. With LINQ, a query is a first-class language construct, just like classes, methods, events.

For a developer who writes queries, the most visible “language-integrated” part of LINQ is the query expression. Query expressions are written in a declarative query syntax. By using query syntax, you can perform filtering, ordering, and grouping operations on data sources with a minimum of code. You use the same basic query expression patterns to query and transform data in SQL databases, ADO .NET Datasets, XML documents and streams, and .NET collections.

The following example shows the complete query operation. The complete operation includes creating a data source, defining the query expression, and executing the query in a foreach statement.

// Specify the data source. int[] scores = { 97, 92, 81, 60 }; // Define the query expression. IEnumerable scoreQuery = from score in scores where score > 80 select score; // Execute the query. foreach (int i in scoreQuery) { Console.Write(i + ” “); } // Output: 97 92 81

Query expression overview

Query expressions can be used to query and to transform data from any LINQ-enabled data source. For example, a single query can retrieve data from a SQL database, and produce an XML stream as output.

Query expressions are easy to grasp because they use many familiar C# language constructs.

The variables in a query expression are all strongly typed, although in many cases you do not have to provide the type explicitly because the compiler can infer it. For more information, see Type relationships in LINQ query operations.

A query is not executed until you iterate over the query variable, for example, in a foreach statement. For more information, see Introduction to LINQ queries.

At compile time, query expressions are converted to Standard Query Operator method calls according to the rules set forth in the C# specification. Any query that can be expressed by using query syntax can also be expressed by using method syntax. However, in most cases query syntax is more readable and concise. For more information, see C# language specification and Standard query operators overview.

As a rule when you write LINQ queries, we recommend that you use query syntax whenever possible and method syntax whenever necessary. There is no semantic or performance difference between the two different forms. Query expressions are often more readable than equivalent expressions written in method syntax.

Some query operations, such as Count or Max, have no equivalent query expression clause and must therefore be expressed as a method call. Method syntax can be combined with query syntax in various ways. For more information, see Query syntax and method syntax in LINQ.

Query expressions can be compiled to expression trees or to delegates, depending on the type that the query is applied to. IEnumerable queries are compiled to delegates. IQueryable and IQueryable queries are compiled to expression trees. For more information, see Expression trees.

Next steps

To learn more details about LINQ, start by becoming familiar with some basic concepts in Query expression basics, and then read the documentation for the LINQ technology in which you are interested:

To gain a deeper understanding of LINQ in general, see LINQ in C#.

To start working with LINQ in C#, see the tutorial Working with LINQ.

LINQ – Overview

LINQ – Overview

Advertisements

Developers across the world have always encountered problems in querying data because of the lack of a defined path and need to master a multiple of technologies like SQL, Web Services, XQuery, etc.

Introduced in Visual Studio 2008 and designed by Anders Hejlsberg, LINQ (Language Integrated Query) allows writing queries even without the knowledge of query languages like SQL, XML etc. LINQ queries can be written for diverse data types.

Example of a LINQ query

C#

using System; using System.Linq; class Program { static void Main() { string[] words = {“hello”, “wonderful”, “LINQ”, “beautiful”, “world”}; //Get only short words var shortWords = from word in words where word.Length <= 5 select word; //Print each word out foreach (var word in shortWords) { Console.WriteLine(word); } Console.ReadLine(); } } VB Module Module1 Sub Main() Dim words As String() = {"hello", "wonderful", "LINQ", "beautiful", "world"} ' Get only short words Dim shortWords = From word In words _ Where word.Length <= 5 _ Select word ' Print each word out. For Each word In shortWords Console.WriteLine(word) Next Console.ReadLine() End Sub End Module When the above code of C# or VB is compiled and executed, it produces the following result − hello LINQ world Syntax of LINQ There are two syntaxes of LINQ. These are the following ones. Lamda (Method) Syntax var longWords = words.Where( w ⇒ w.length > 10); Dim longWords = words.Where(Function(w) w.length > 10)

Query (Comprehension) Syntax

var longwords = from w in words where w.length > 10; Dim longwords = from w in words where w.length > 10

Types of LINQ

The types of LINQ are mentioned below in brief.

LINQ to Objects

LINQ to XML(XLINQ)

LINQ to DataSet

LINQ to SQL (DLINQ)

LINQ to Entities

Apart from the above, there is also a LINQ type named PLINQ which is Microsoft’s parallel LINQ.

LINQ Architecture in .NET

LINQ has a 3-layered architecture in which the uppermost layer consists of the language extensions and the bottom layer consists of data sources that are typically objects implementing IEnumerable or IQueryable generic interfaces. The architecture is shown below.

Query Expressions

Query expression is nothing but a LINQ query, expressed in a form similar to that of SQL with query operators like Select, Where and OrderBy. Query expressions usually start with the keyword “From”.

To access standard LINQ query operators, the namespace System.Query should be imported by default. These expressions are written within a declarative query syntax which was C# 3.0.

Below is an example to show a complete query operation which consists of data source creation, query expression definition and query execution.

C#

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Operators { class LINQQueryExpressions { static void Main() { // Specify the data source. int[] scores = new int[] { 97, 92, 81, 60 }; // Define the query expression. IEnumerable scoreQuery = from score in scores where score > 80 select score; // Execute the query. foreach (int i in scoreQuery) { Console.Write(i + ” “); } Console.ReadLine(); } } }

When the above code is compiled and executed, it produces the following result −

97 92 81

Extension Methods

Introduced with .NET 3.5, Extension methods are declared in static classes only and allow inclusion of custom methods to objects to perform some precise query operations to extend a class without being an actual member of that class. These can be overloaded also.

In a nutshell, extension methods are used to translate query expressions into traditional method calls (object-oriented).

Difference between LINQ and Stored Procedure

There is an array of differences existing between LINQ and Stored procedures. These differences are mentioned below.

Stored procedures are much faster than a LINQ query as they follow an expected execution plan.

It is easy to avoid run-time errors while executing a LINQ query than in comparison to a stored procedure as the former has Visual Studio’s Intellisense support as well as full-type checking during compile-time.

LINQ allows debugging by making use of .NET debugger which is not in case of stored procedures.

LINQ offers support for multiple databases in contrast to stored procedures, where it is essential to re-write the code for diverse types of databases.

Deployment of LINQ based solution is easy and simple in comparison to deployment of a set of stored procedures.

Need For LINQ

Prior to LINQ, it was essential to learn C#, SQL, and various APIs that bind together the both to form a complete application. Since, these data sources and programming languages face an impedance mismatch; a need of short coding is felt.

Below is an example of how many diverse techniques were used by the developers while querying a data before the advent of LINQ.

SqlConnection sqlConnection = new SqlConnection(connectString); SqlConnection.Open(); System.Data.SqlClient.SqlCommand sqlCommand = new SqlCommand(); sqlCommand.Connection = sqlConnection; sqlCommand.CommandText = “Select * from Customer”; return sqlCommand.ExecuteReader (CommandBehavior.CloseConnection)

Interestingly, out of the featured code lines, query gets defined only by the last two. Using LINQ, the same data query can be written in a readable color-coded form like the following one mentioned below that too in a very less time.

Northwind db = new Northwind(@”C:\Data\Northwnd.mdf”); var query = from c in db.Customers select c;

Advantages of LINQ

LINQ offers a host of advantages and among them the foremost is its powerful expressiveness which enables developers to express declaratively. Some of the other advantages of LINQ are given below.

LINQ offers syntax highlighting that proves helpful to find out mistakes during design time.

LINQ offers IntelliSense which means writing more accurate queries easily.

Writing codes is quite faster in LINQ and thus development time also gets reduced significantly.

LINQ makes easy debugging due to its integration in the C# language.

Viewing relationship between two tables is easy with LINQ due to its hierarchical feature and this enables composing queries joining multiple tables in less time.

LINQ allows usage of a single LINQ syntax while querying many diverse data sources and this is mainly because of its unitive foundation.

LINQ is extensible that means it is possible to use knowledge of LINQ to querying new data source types.

LINQ offers the facility of joining several data sources in a single query as well as breaking complex problems into a set of short queries easy to debug.

LINQ offers easy transformation for conversion of one data type to another like transforming SQL data to XML data.

LINQ: Query Syntax vs. Method syntax

LINQ:

LINQ: Query Syntax vs. Method syntax

In the previous article, we got a quick glimpse of how both LINQ syntaxes look, but let’s just get them on the table again right next to each other, so you are sure of what we’ll be discussing in this article:

var listOfNames = new List()

{

“John Doe”,

“Jane Doe”,

“Jenna Doe”,

“Joe Doe”

};

// Query syntax

var qNames = from name in listOfNames where name.Length <= 8 select name; // Method syntax var mNames = listOfNames.Where(name => name.Length <= 8); While the two lines will accomplish the exact same thing, the syntactical difference is quite clear: The query syntax looks more like other query languages, e.g. SQL and less like a regular C# statement. The method syntax, on the other hand, looks very much like the rest of the C# code you have seen in this tutorial. So, the biggest difference is definitely just the syntax and therefore, you will see both variations used when reading C# articles and finding answers to questions you might have. It seems that the query syntax is slightly more popular because some people find it easier to read than the method syntax - these might be people who are used to expressing data retrieval operations in SQL anyway. On the other hand, if you have never used a query language like SQL before, but you have some C# experience, then you might find the method syntax easier to read. Also, for at least a couple of operations, like counting the items in the result of the query, you will have to use the method syntax. Lambda Expressions In the method syntax example, you might notice something that you haven't seen before, as a parameter to the Where() method. It looks like this: name => name.Length <= 8 This is called a Lambda Expression and while it's not a specific piece of LINQ functionality, it's used A LOT in the world of LINQ. Therefore you will also see it a lot in the following articles, and while I will go into greater details about Lambda Expressions in another article, this is a good time to get a very basic understanding of how they work. It's actually quite simple. A Lambda Expression has a left side and a right side, divided by the => operator (not to be confused with the “greater than or equal to”-operator, which looks like this: >=).

On the left side, we have the input parameter(s) – there can be several, but in our example, there’s just one, which is the name variable. In this case, it comes from the Where() method, from iterating over our list of names and we get to pick the name. I chose “name”, because that’s what you’ll find in a list of names, but you could also call it “x”, “z”, “foobar” or anything else.

On the right side, we have the expression/statement part. This is where we generate the expected result – in this case, a boolean value telling the Where() method whether to include the name in question or not. We answer that with an expression, saying that we want to include the name if it has a length of 8 (or less) characters. We can (but are not required to) use the input (left side) to determine this. Again, we refer to it as “name”, but we could have called it “x” instead – in that case, the statement would have looked like this:

var mNames = listOfNames.Where(x => x.Length <= 8); Lambda Expressions are about more than just LINQ queries, but as mentioned, they are important when using LINQ - you will see that in the next articles. If you want to know more about Lambda Expressions in general, have a look elsewhere in this tutorial where the topic will be covered. Summary LINQ comes in two syntactical flavors: The Query and the Method syntax. They can do almost the same, but while the query syntax is almost a new language within C#, the method syntax looks just like regular C# method calls. In this tutorial, we will mostly be using the method syntax, when we discuss all the possible operations available with LINQ in the next articles.

What is LINQ (Language Integrated Query)?

LINQ (Language Integrated Query) is a Microsoft programming model and methodology that essentially adds formal query capabilities into Microsoft .NET-based programming languages. LINQ offers a compact, expressive, and intelligible syntax for manipulating data. The real value of LINQ comes from its ability to apply the same query to an SQL database, a DataSet, an array of objects in memory and to many other types of data as well. LINQ requires the presence of specific language extensions.

LINQ uses an SQL-like syntax to make query expressions well beyond the capabilities of embedded SQL as implemented in programming languages. That’s because embedded SQL uses a simplified, streamlined syntax to add SQL statements to other programming languages, where there’s no attempt to integrate such statements into the native syntax and typing mechanisms. Thus, you can’t invoke native language structures such as functions in embedded SQL statements, as you can using LINQ, because it is implemented to use native syntax, structures, and typing mechanisms. Furthermore, LINQ may be used to access all kinds of data, whereas embedded SQL is limited to addressing only databases that can handle SQL queries.

Sample LINQ Queries

Sample LINQ Queries

In this section, you will learn some complex LINQ queries. We will use the following Student and Standard collection for our queries.

Sample Collections: IList < Student > studentList = new List < Student >() { new Student () { StudentID = 1, StudentName = “John” , Age = 18, StandardID = 1 } , new Student () { StudentID = 2, StudentName = “Steve” , Age = 21, StandardID = 1 } , new Student () { StudentID = 3, StudentName = “Bill” , Age = 18, StandardID = 2 } , new Student () { StudentID = 4, StudentName = “Ram” , Age = 20, StandardID = 2 } , new Student () { StudentID = 5, StudentName = “Ron” , Age = 21 } }; IList < Standard > standardList = new List < Standard >() { new Standard (){ StandardID = 1, StandardName= “Standard 1” }, new Standard (){ StandardID = 2, StandardName= “Standard 2” }, new Standard (){ StandardID = 3, StandardName= “Standard 3” } };

Multiple Select and where operator

Example: Multiple Select and where Operator var studentNames = studentList.Where(s => s.Age > 18) .Select(s => s) .Where(st => st.StandardID > 0) .Select(s => s.StudentName);

Output:

Steve

Ram

The following query returns Enumerable of anonymous object that has only StudentName property:

Example: LINQ Query returns Collection of Anonymous Objects var teenStudentsName = from s in studentList where s.age > 12 && s.age < 20 select new { StudentName = s.StudentName }; teenStudentsName.ToList().ForEach(s => Console .WriteLine(s.StudentName));

Output:

John

Bill

Group By

The following query returns list students group by StandardID:

Example: LINQ GroupBy Query – C# var studentsGroupByStandard = from s in studentList group s by s.StandardID into sg orderby sg.Key select new { sg.Key, sg }; foreach ( var group in studentsGroupByStandard) { Console .WriteLine( “StandardID {0}:” , group.Key); group.sg.ToList().ForEach(st => Console .WriteLine(st.StudentName )); }

Output:

StandardID 0:

Ron

StandardID 1:

John

Steve

StandardID 2:

Bill

Ram

The output includes Ron who doesn’t have any StandardID. So Ron falls under StandardID 0.

To remove a student who doesn’t have a StandardID, use a where operator before the group operator:

Example: LINQ GroupBy Query – C# var studentsGroupByStandard = from s in studentList where s.StandardID > 0 group s by s.StandardID into sg orderby sg.Key select new { sg.Key, sg };

Output:

StandardID 1:

John

Steve

StandardID 2:

Bill

Ram

Left outer join

Use left outer join to display students under each standard. Display the standard name even if there is no student assigned to that standard.

Example: LINQ Left Outer Join – C# var studentsGroup = from stad in standardList join s in studentList on stad.StandardID equals s.StandardID into sg select new { StandardName = stad.StandardName, Students = sg }; foreach ( var group in studentsGroup) { Console .WriteLine(group.StandardName); group.Students.ToList().ForEach(st => Console .WriteLine(st.StudentName)); }

Output:

Standard 1:

John

Steve

Standard 2:

Bill

Ram

Standard 3:

In the following example of group by query, we sort the group and select only StudentName:

Example: LINQ Left Outer Join – C# var studentsWithStandard = from stad in standardList join s in studentList on stad.StandardID equals s.StandardID into sg from std_grp in sg orderby stad.StandardName, std_grp.StudentName select new { StudentName = std_grp.StudentName, StandardName = stad.StandardName }; foreach ( var group in studentsWithStandard) { Console .WriteLine( “{0} is in {1}” , group.StudentName, group.StandardName); }

Output:

John is in Standard 1

Steve is in Standard 1

Bill is in Standard 2

Ram is in Standard 2

Sorting

The following query returns list of students by ascending order of StandardID and Age.

Example: Sorting var sortedStudents = from s in studentList orderby s.StandardID, s.age select new { StudentName = s.StudentName, Age = s.age, StandardID = s.StandardID }; sortedStudents.ToList().ForEach(s => Console .WriteLine( “Student Name: {0}, Age: {1}, StandardID: {2}” , s.StudentName, s.Age , s.StandardID));

Output:

Student Name: Ron, Age: 21, StandardID: 0

Student Name: John, Age: 18, StandardID: 1

Student Name: Steve, Age: 21, StandardID: 1

Student Name: Bill, Age: 18, StandardID: 2

Student Name: Ram, Age: 20, StandardID: 2

Inner Join

Example: LINQ Inner join – C# var studentWithStandard = from s in studentList join stad in standardList on s.StandardID equals stad.StandardID select new { StudentName = s.StudentName, StandardName = stad.StandardName }; studentWithStandard.ToList().ForEach(s => Console.WriteLine( “{0} is in {1}” , s.StudentName, s.StandardName ));

Output:

John is in Standard 1

Steve is in Standard 1

Bill is in Standard 2

Ram is in Standard 2

Nested Query

C#: var nestedQueries = from s in studentList where s.age > 18 && s.StandardID == ( from std in standardList where std.StandardName == “Standard 1” select std.StandardID).FirstOrDefault() select s; nestedQueries.ToList().ForEach(s => Console .WriteLine(s.StudentName));

Output:

Steve

10 Resources for Learning LINQ

LINQ is something I just take for granted with C# anymore, since it’s been around for over a decade, but some years back I was fascinated with it. I probably used it, like any newly-discovered golden hammer, for things I shouldn’t have. Hopefully I’ve mellowed out in my LINQ usage since then. 🙂

Two things make it worth learning:

It reduces extra lines of code. It reads more naturally, like SQL.

Take this fairly simple example, where we want to find the highest paid employee. In one case, we need temp variables, and a loop, and some logic to store off the value but only if it’s the highest so far. In the second, we just tell it to order by largest first and grab the top value.

If all we want is the highest dollar amount, we’d still need a loop much like the first example. Or we could use LINQ and tell it to grab the max salary, done!

using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { // A list of employees, which would come from a database var emps = new List { new Employee { Name = “Ann”, Age = 31, Gender = “F”, Salary = 50000 }, new Employee { Name = “Brian”, Age = 25, Gender = “M”, Salary = 40000 }, new Employee { Name = “Cara”, Age = 50, Gender = “F”, Salary = 65000 }, new Employee { Name = “Dave”, Age = 33, Gender = “M”, Salary = 52000 } }; // Loop through them all to find the highest salary var highestSalary = 0m; var highestSalaryName = “”; foreach (var emp in emps) { if (emp.Salary > highestSalary) { highestSalary = emp.Salary; highestSalaryName = emp.Name; } } Console.WriteLine($”{highestSalaryName} earns the highest salary of ${highestSalary}.\r

“); // output: Cara earns the highest salary of $65000. // Same thing, but a single line of LINQ var winner = emps.OrderByDescending(emp => emp.Salary).First(); Console.WriteLine($”{winner.Name} earns the highest salary of ${winner.Salary}.\r

“); // output: Cara earns the highest salary of $65000. // If we don’t care about who, our LINQ gets even shorter Console.WriteLine($”The highest salary is ${emps.Max(emp => emp.Salary)}.\r

“); // output: The highest salary is $65000. } } public class Employee { public string Name { get; set; } public int Age { get; set; } public decimal Salary { get; set; } public string Gender { get; set; } }

You can browse the source code if you really want to get into the guts of things, but in essence, LINQ methods either:

Expect a collection ( IEnumerable ) and pass back a collection of the same type, like filtering with Where , sorting with OrderBy , dividing into chunks with GroupBy , paring down the resultset with Select , etc.

) and pass back a collection of the same type, like filtering with , sorting with , dividing into chunks with , paring down the resultset with , etc. Perform some operation that returns a result, like Max , Min , Count , ToList , etc.

It takes some time to get used to, but there are a lot of resources out there for learning LINQ. They’re not all the same though, and a style that works for one person might not click for someone else, so let’s check a few out. These are just the tip of the iceberg though.

DotNet Try

I think this used to be a static site, the contents of which are archived elsewhere, but it’s gotten an upgrade. You have to do a small bit of configuration to install DotNet Try, then clone the try-samples repo (I wrote about it previously). Once you do, you get a comprehensive tutorial that advances through the different LINQ commands, complete with interactive code snippets you can change and run right in the browser.

Channel 9

If you prefer videos instead, there’s a series on Microsoft’s Channel 9 that uses the above examples. So get the above working, then step through the examples with Bill Wagner and Mika Dumont.

LINQSamples

LINQSamples has some good tutorials that explain important concepts, including method vs query syntax (yep, there’s two ways to write LINQ statements) and deferred execution (write your statement now, execute it later when you need it).

There’s also a comprehensive section on all the available LINQ commands, with examples written in C#, F#, and VB.NET.

Most sites don’t provide for an interactive experience in the browser, but that’s okay. If you don’t have a local setup to try all these, visit .NET Fiddle, or just expand on this fiddle that I setup for my example at the top of this post.

Dot Net Tutorials

There’s a lot here, but if you read nothing else, at least check out their section on the architecture of LINQ. They make a great case for how learning one syntax can save you a lot of time when you have to query different data sources.

There’s a whole variety of data sources out there (sql, xml, text files, collection of in-memory objects, etc), but as long as there’s a provider to translate LINQ to whatever each one natively needs, you can use one syntax for them all. For example, querying XML with LINQ is built into the .NET framework, and Entity Framework can help us query databases with LINQ.

IAmTimCorey (YouTube)

This is a good intro to some basic LINQ commands. Tim Corey runs through examples for ordering and filtering a list of people, and he goes nice and slow. He’s got a link in the comments to get his sample code too, so you can go through it with him.

Code Project #1

Here’s an older article, from about the time LINQ was introduced, but it’s comprehensive, most of the basics still apply anyway, and the author included source code. You’ll need a (free) CodeProject account to download the zip file, but after letting VS2019 spend a few seconds upgrading the project, it ran just fine.

Note that the author’s examples all use the query syntax, so you’re only getting one half of the picture, but maybe that’s your thing since query syntax more closely resembles SQL. I prefer the method syntax that looks more like standard C#, but that’s just personal preference!

Code Project #2 (Jovan Popovic)

Here’s another one written a few years later, by someone who’s a project manager at Microsoft.

The first third of the article provides a nice overview of some concepts in LINQ, like how it operates on collections, is similar to SQL, and how you can create and manipulate anonymous classes on-the-fly. That’s the reason we were given the var keyword, btw, although it makes for easier-to-read code in general too.

It doesn’t look like he provides a link to download his code, but he does layout exactly what his classes look like that he used throughout the article, so you can recreate them locally.

TutorialsTeacher

There’s a lot going on in this one too. It covers the basics of LINQ, or you can skip to a specific keyword if you want to see what a command does in LINQ. It also covers more advanced topics like expression trees.

Trees aren’t something you need to understand to use LINQ, but I would suggest reading about deferred execution. Briefly, it’s possible to write a LINQ statement, but not execute it right away. You can modify a collection more before running it, or run it multiple times. Think of it like writing an SQL statement in SSMS, but then not hitting F5 until later.

MSDN Docs

They’re pretty dry, but you can’t get more authoritative than the source. If you run into a problem, check out the MSDN docs to see if there’s a note or warning (usually in the “Remarks” section) for the LINQ command you’re trying to use.

LINQPad

Last but not least, there’s LINQPad. This isn’t a tutorial per se, but it’s much more. You can connect to actual databases, and execute your LINQ statements against them directly. If you pay $60 for the pro edition, you get autocomplete, which anyone who’s used Visual Studio with intellisense would understand how convenient that is.

There’s a “Tutorial and Reference” section in the Help menu, which shows you how to use LINQPad and run simple queries.

You can modify the queries and try running them again, to see the effect. I converted their query syntax to method syntax, and made a small change, below.

LINQPad even installs a sample database for you to use, which you can run queries against. Very convenient for learning LINQ!

Good luck! If you find any other great resources and want to share them, reach out or leave a comment below…

LINQ Query Samples

In this article you will find several examples of LINQ queries that may be useful for your application development. For the wide list refer to 101 LINQ Samples.

You can download the database scripts from our site to run the following scripts.

SELECT with Implicit join SELECT with Implicit join

This query shows to us how we can use implicit join in LINQ-statements. We will join Products and Category entities by the Product.Category field.

LINQ: C# csharp Copy Code Copy Code var query = from product in db.Products select new { Name = product.Productname, Price = product.Unitprice, Category = product.Category.Categoryname }; foreach (var element in query) { Console.WriteLine(”

” + element.Name + ” from ” + element.Category + ” costs ” + element.Price + ” per unit.”); }

Visual Basic Copy Code Copy Code Dim query = From product In db.Products _ Select New With { .Name = product.Productname, _ .Price = product.Unitprice, _ .Category = product.Category.Categoryname } For Each element In query Console.WriteLine(VbCrLf & element.Name & ” from ” & element.Category & ” costs ” & element.Price & ” per unit.”) Next The native SQL-statements generated for the LINQ code are presented below:

Generated SQL for MySQL DBMS Generated SQL for MySQL DBMS

SELECT t1.ProductName AS Productname, t1.UnitPrice AS Unitprice, t2.CategoryName AS Categoryname FROM northwindef.products t1 LEFT OUTER JOIN northwindef.categories t2 ON t1.CategoryID = t2.CategoryID

Generated SQL for Oracle DBMS Generated SQL for Oracle DBMS

SELECT t1.”ProductName” AS “Productname”, t1.”UnitPrice” AS “Unitprice”, t2.”CategoryName” AS “Categoryname” FROM NORTHWINDEF.”Products” t1 LEFT OUTER JOIN NORTHWINDEF.”Categories” t2 ON t1.”CategoryID” = t2.”CategoryID”

Generated SQL for MS SQL Server DBMS Generated SQL for MS SQL Server DBMS

SELECT [t0].[ProductName] AS [Name], [t0].[UnitPrice] AS [Price], [t1].[CategoryName] AS [Category] FROM [dbo].[Products] AS [t0] LEFT OUTER JOIN [dbo].[Categories] AS [t1] ON [t1].[CategoryID] = [t0].[CategoryID]

Generated SQL for PostgreSQL DBMS Generated SQL for PostgreSQL DBMS

SELECT t1.”ProductName” AS “Productname”, t1.”UnitPrice” AS “Unitprice”, t2.”CategoryName” AS “Categoryname” FROM public .”Products” t1 LEFT OUTER JOIN public .”Categories” t2 ON t1.”CategoryID” = t2.”CategoryID”

Generated SQL for SQLite DBMS Generated SQL for SQLite DBMS

SELECT t1.ProductName AS Productname, t1.UnitPrice AS Unitprice, t2.CategoryName AS Categoryname FROM Products t1 LEFT OUTER JOIN Categories t2 ON (t1.CategoryID = t2.CategoryID) OR ((t1.CategoryID IS NULL ) AND (t2.CategoryID IS NULL ))

Results: Results:

Chai from Beverages costs 18 per unit.

Chang from Beverages costs 19 per unit.

As we can easily see, this query takes a subset of Product columns. Also we have an implicit join of the Products and Categories tables in the product.Category access.

SELECT with two from clauses SELECT with two from clauses

This query shows to us how we can build a query with two from clauses. We will select data from two entities: Customers and Orders.

LINQ: C# csharp Copy Code Copy Code var query = from c in db.Customers from o in c.Orders select new { c.Contactname, o.Orderid, o.Orderdate }; foreach (var element in query) { Console.WriteLine(”

” + element.Contactname + ” made order ” + element.Orderid + ” on ” + element.Orderdate + “.”); }

Visual Basic Copy Code Copy Code Dim query = From c In db.Customers _ From o in db.Orders _ Select New With { c.Contactname, o.Orderid, o.Orderdate } For Each element In query Console.WriteLine(VbCrLf & element.Contactname & ” made order ” & element.Orderid & _ ” on ” & element.Orderdate & “.”) Next The native SQL-statements generated for the LINQ code are presented below:

Generated SQL for MySQL DBMS Generated SQL for MySQL DBMS

SELECT t1.ContactName AS Contactname, t2.OrderID AS Orderid, t2.OrderDate AS Orderdate FROM northwindef.customers t1, northwindef.orders t2 WHERE t1.CustomerID = t2.CustomerID

Generated SQL for Oracle DBMS Generated SQL for Oracle DBMS

SELECT t1.”ContactName” AS “Contactname”, t2.”OrderID” AS “Orderid”, t2.”OrderDate” AS “Orderdate” FROM NORTHWINDEF.”Customers” t1, NORTHWINDEF.”Orders” t2 WHERE t1.”CustomerID” = t2.”CustomerID”

Generated SQL for MS SQL Server DBMS Generated SQL for MS SQL Server DBMS

SELECT [t0].[ContactName] AS [Contactname], [t1].[OrderID] AS [Orderid], [t1].[OrderDate] AS [Orderdate] FROM [dbo].[Customers] AS [t0], [dbo].[Orders] AS [t1] WHERE [t1].[CustomerID] = [t0].[CustomerID]

Generated SQL for PostgreSQL DBMS Generated SQL for PostgreSQL DBMS

SELECT t1.”ContactName” AS “Contactname”, t2.”OrderID” AS “Orderid”, t2.”OrderDate” AS “Orderdate” FROM public .”Customers” t1, public .”Orders” t2 WHERE t1.”CustomerID” = t2.”CustomerID”

Generated SQL for SQLite DBMS Generated SQL for SQLite DBMS

SELECT t1.ContactName AS Contactname, t2.OrderID AS Orderid, t2.OrderDate AS Orderdate FROM Customers t1, Orders t2 WHERE t1.CustomerID = t2.CustomerID

Results: Results: Maria Anders made order 10643 on 08.25.1997.

Maria Anders made order 10692 on 10.03.1997.

So, we are able to query two tables in one query easily using LinqConnect.

SELECT with two from clauses and where clauses SELECT with two from clauses and where clauses

This query is very similar to previous but we define a conditions to Customers and Orders entities. We select only customers from “USA” and orders older than 1998.

LINQ: C# csharp Copy Code Copy Code var query = from c in db.Customers where c.Country == “USA” from o in c.Orders where o.Orderdate >= new DateTime(1998, 1, 1) select new { c.Contactname, o.Orderid, o.Orderdate }; foreach (var element in query) { Console.WriteLine(”

” + element.Contactname + ” made order ” + element.Orderid + ” on ” + element.Orderdate + “.”); }

Visual Basic Copy Code Copy Code Dim query = From c In db.Customers _ Where c.Country = “USA” _ From o In db.Orders _ Where o.Orderdate >= New DateTime (1998, 1, 1) _ Select New With { c.Contactname, o.Orderid, o.Orderdate } For Each element In query Console.WriteLine(VbCrLf & element.Contactname & ” made order ” & element.Orderid &_ ” on ” & element.Orderdate & “.”) Next The native SQL-statements generated for the LINQ code are presented below:

Generated SQL for MySQL DBMS Generated SQL for MySQL DBMS

SELECT t1.ContactName, t2.OrderID, t2.OrderDate FROM northwindef.customers t1, northwindef.orders t2 WHERE (t2.OrderDate >= :p0) AND (t1.Country = :p1) AND (t1.CustomerID = t2.CustomerID) ParameterName = p0 DbType = DateTime Value = 01.01.1998 0:00:00 ParameterName = p1 DbType = AnsiString Value = USA

Generated SQL for Oracle DBMS Generated SQL for Oracle DBMS

SELECT t1.”ContactName”, t2.”OrderID”, t2.”OrderDate” FROM NORTHWINDEF.”Customers” t1, NORTHWINDEF.”Orders” t2 WHERE (t2.”OrderDate” >= :p0) AND (t1.”Country” = :p1) AND (t1.”CustomerID” = t2.”CustomerID”) ParameterName = p0 DbType = DateTime Value = 01.01.1998 0:00:00 ParameterName = p1 DbType = String Value = USA

Generated SQL for MS SQL Server DBMS Generated SQL for MS SQL Server DBMS

SELECT [t0].[ContactName] AS [Contactname], [t1].[OrderID] AS [Orderid], [t1].[OrderDate] AS [Orderdate] FROM [dbo].[Customers] AS [t0], [dbo].[Orders] AS [t1] WHERE ([t1].[OrderDate] >= @p0) AND ([t0].[Country] = @p1) AND ([t1].[CustomerID] = [t0].[CustomerID]) — @p0: Input DateTime (Size = 0; Prec = 0; Scale = 0) [01.01.1998 0:00:00] — @p1: Input NVarChar (Size = 3; Prec = 0; Scale = 0) [USA]

Generated SQL for PostgreSQL DBMS Generated SQL for PostgreSQL DBMS

SELECT t1.”ContactName”, t2.”OrderID”, t2.”OrderDate” FROM public .”Customers” t1, public .”Orders” t2 WHERE (t2.”OrderDate” >= :p0) AND (t1.”Country” = :p1) AND (t1.”CustomerID” = t2.”CustomerID”) ParameterName = p0 DbType = DateTime Value = 01.01.1998 0:00:00 ParameterName = p1 DbType = AnsiString Value = USA

Generated SQL for SQLite DBMS Generated SQL for SQLite DBMS

SELECT t1.ContactName AS ContactName, t2.OrderID AS OrderID, t2.OrderDate AS OrderDate FROM Customers t1, Orders t2 WHERE (t2.OrderDate >= :p0) AND (t1.Country = :p1) AND (t1.CustomerID = t2.CustomerID) ParameterName = p0 DbType = DateTime Value = 01.01.1998 0:00:00 ParameterName = p1 DbType = String Value = USA

Results: Results: Howard Snyder made order 10816 on 01.06.1998.

Howard Snyder made order 10936 on 03.09.1998.

Here we can see the query which narrows customers to only USA-located ones and orders are narrowed to the ones after Jan 1, 1999. It is good solution from the performance point of view.

SELECT with more complicated where clause SELECT with more complicated where clause

In this query we define complicated Where clause – we define customer location and first symbol of its name.

LINQ: C# csharp Copy Code Copy Code var query = from c in db.Customers where c.Country == “USA” && c.Contactname.StartsWith(“J”) select new { c.Contactname, c.Address }; foreach (var element in query) { Console.WriteLine(”

” + element.Contactname + ” is located at ” + element.Address); }

Visual Basic Copy Code Copy Code Dim query = From c In db.Customers _ Where c.Country = “USA” And c.Contactname.StartsWith(“J”) _ Select New With { c.Contactname, c.Address } For Each element In query Console.WriteLine(VbCrLf & element.Contactname & ” is located at ” & element.Address) Next The native SQL-statements generated for the LINQ code are presented below:

Generated SQL for MySQL DBMS Generated SQL for MySQL DBMS

SELECT t1.ContactName, t1.Address FROM northwindef.customers t1 WHERE (t1.Country = :p0) AND (BINARY t1.ContactName LIKE :p1) ParameterName = p0 DbType = AnsiString Value = USA ParameterName = p1 DbType = AnsiString Value = J%

Generated SQL for Oracle DBMS Generated SQL for Oracle DBMS

SELECT t1.”ContactName”, t1.”Address” FROM NORTHWINDEF.”Customers” t1 WHERE (t1.”Country” = :p0) AND (t1.”ContactName” LIKE :p1) ParameterName = p0 DbType = String Value = USA ParameterName = p1 DbType = String Value = J%

Generated SQL for MS SQL Server DBMS Generated SQL for MS SQL Server DBMS

SELECT [t0].[ContactName] AS [Contactname], [t0].[Address] FROM [dbo].[Customers] AS [t0] WHERE ([t0].[Country] = @p0) AND ([t0].[ContactName] LIKE @p1) — @p0: Input NVarChar (Size = 3; Prec = 0; Scale = 0) [USA] — @p1: Input NVarChar (Size = 2; Prec = 0; Scale = 0) [J%]

Generated SQL for PostgreSQL DBMS Generated SQL for PostgreSQL DBMS

SELECT t1.”ContactName”, t1.”Address” FROM public .”Customers” t1 WHERE (t1.”Country” = :p0) AND (t1.”ContactName” LIKE :p1) ParameterName = p0 DbType = AnsiString Value = USA ParameterName = p1 DbType = AnsiString Value = J%

Generated SQL for SQLite DBMS Generated SQL for SQLite DBMS

SELECT t1.ContactName AS ContactName, t1.Address AS Address FROM Customers t1 WHERE (t1.Country = :p0) AND (t1.ContactName LIKE :p1) ParameterName = p0 DbType = String Value = USA ParameterName = p1 DbType = String Value = J%

Results: Results: John Steel is located at 12 Orchestra Terrace

Jaime Yorres is located at 87 Polk St. Suite 5

So, where clause can be compound and contain some functions.

SELECT with ordering and paging SELECT with ordering and paging

In this query we define conditions for paging and ordering. To do it orderby clause, and Skip and Take functions are used.

LINQ: C# csharp Copy Code Copy Code var query = (from p in db.Products orderby p.Productname select p).Skip(10).Take(10); foreach (var element in query) { Console.WriteLine(”

” + element.Productname); }

Visual Basic Copy Code Copy Code Dim query = (From p In db.Products _ Order By p.Productname _ Select p).Skip(10).Take(10) For Each element In query Console.WriteLine(VbCrLf & element.Productname) Next The native SQL-statements generated for the LINQ code are presented below:

Generated SQL for MySQL DBMS Generated SQL for MySQL DBMS

SELECT t1.ProductID, t1.ProductName, t1.SupplierID, t1.CategoryID, t1.QuantityPerUnit, t1.UnitPrice, t1.UnitsInStock, t1.UnitsOnOrder, t1.ReorderLevel, t1.Discontinued, t1.DiscontinuedDate FROM northwindef.products t1 ORDER BY t1.ProductName LIMIT :p0, :p1 ParameterName = p0 DbType = Int32 Value = 10 ParameterName = p1 DbType = Int32 Value = 10

Generated SQL for Oracle DBMS Generated SQL for Oracle DBMS

SELECT t1.”ProductID”, t1.”ProductName”, t1.”SupplierID”, t1.”CategoryID”, t1.”QuantityPerUnit”, t1.”UnitPrice”, t1.”UnitsInStock”, t1.”UnitsOnOrder”, t1.”ReorderLevel”, t1.”Discontinued”, t1.”DiscontinuedDate” FROM ( SELECT t2.”ProductID”, t2.”ProductName”, t2.”SupplierID”, t2.”CategoryID”, t2.”QuantityPerUnit”, t2.”UnitPrice”, t2.”UnitsInStock”, t2.”UnitsOnOrder”, t2.”ReorderLevel”, t2.”Discontinued”, t2.”DiscontinuedDate”, ROW_NUMBER() OVER ( ORDER BY t2.”ProductName”) AS “rnum” FROM NORTHWINDEF.”Products” t2 ORDER BY t2.”ProductName” ) t1 WHERE (t1.”rnum” > :p0) AND (t1.”rnum” <= :p1) ParameterName = p0 DbType = Int32 Value = 10 ParameterName = p1 DbType = Int32 Value = 20 Generated SQL for MS SQL Server DBMS Generated SQL for MS SQL Server DBMS SELECT [t1].[ProductID] AS [Productid], [t1].[ProductName] AS [Productname], [t1].[SupplierID] AS [Supplierid], [t1].[CategoryID] AS [Categoryid], [t1].[QuantityPerUnit] AS [Quantityperunit], [t1].[UnitPrice] AS [Unitprice], [t1].[UnitsInStock] AS [Unitsinstock], [t1].[UnitsOnOrder] AS [Unitsonorder], [t1].[ReorderLevel] AS [Reorderlevel], [t1].[Discontinued], [t1].[DiscontinuedDate] AS [Discontinueddate], [t1].[LastEditDate] AS [Lasteditdate], [t1].[CreationDate] AS [Creationdate] FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY [t0].[ProductName]) AS [ROW_NUMBER], [t0].[ProductID], [t0].[ProductName], [t0].[SupplierID], [t0].[CategoryID], [t0].[QuantityPerUnit], [t0].[UnitPrice], [t0].[UnitsInStock], [t0].[UnitsOnOrder], [t0].[ReorderLevel], [t0].[Discontinued], [t0].[DiscontinuedDate], [t0].[LastEditDate], [t0].[CreationDate] FROM [dbo].[Products] AS [t0] ) AS [t1] WHERE [t1].[ROW_NUMBER] BETWEEN @p0 + 1 AND @p0 + @p1 ORDER BY [t1].[ROW_NUMBER] -- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [10] -- @p1: Input Int (Size = 0; Prec = 0; Scale = 0) [10] Generated SQL for PostgreSQL DBMS Generated SQL for PostgreSQL DBMS SELECT t1."ProductID", t1."ProductName", t1."SupplierID", t1."CategoryID", t1."QuantityPerUnit", t1."UnitPrice", t1."UnitsInStock", t1."UnitsOnOrder", t1."ReorderLevel", t1."Discontinued", t1."DiscontinuedDate" FROM public ."Products" t1 ORDER BY t1."ProductName" LIMIT :p0 OFFSET :p1 ParameterName = p0 DbType = Int32 Value = 10 ParameterName = p1 DbType = Int32 Value = 10 Generated SQL for SQLite DBMS Generated SQL for SQLite DBMS SELECT t1.ProductID AS ProductID, t1.ProductName AS ProductName, t1.SupplierID AS SupplierID, t1.CategoryID AS CategoryID, t1.QuantityPerUnit AS QuantityPerUnit, t1.UnitPrice AS UnitPrice, t1.UnitsInStock AS UnitsInStock, t1.UnitsOnOrder AS UnitsOnOrder, t1.ReorderLevel AS ReorderLevel, t1.Discontinued AS Discontinued, t1.DiscontinuedDate AS DiscontinuedDate FROM Products t1 ORDER BY t1.ProductName LIMIT :p0, :p1 ParameterName = p0 DbType = Int32 Value = 10 ParameterName = p1 DbType = Int32 Value = 10 Results: Results: Chocolade Cote de Blaye ... This type of queries is useful in the paging tasks. As you see, the peculiarities of differents DBMSs are taken into account. SELECT with grouping and aggregate functions SELECT with grouping and aggregate functions Using of aggregate functions and group by clause is shown in following query. LINQ: C# csharp Copy Code Copy Code var query = from p in db.Products group p by p.Category into g select new { Category = g.Key.Categoryname, Max = g.Max(c=>c.Unitprice) }; foreach (var element in query) { Console.WriteLine(”

” + “The most expensive product in ” + element.Category + ” category costs ” + element.Max); }

Visual Basic Copy Code Copy Code Dim query = From p In db.Products _ Group p By p.Category Into Group _ Select New With { .Category = Category.Categoryname, .Max = Group.Max(Function(c) c.Unitprice) } For Each element In query Console.WriteLine(VbCrLf & “The most expensive product in ” & element.Category & _ ” category costs ” & element.Max) Next The native SQL-statements generated for the LINQ code are presented below: Generated SQL for MySQL DBMS: Generated SQL for MySQL DBMS:

SELECT t3.CategoryName AS Categoryname, t1.C1 FROM ( SELECT t2.CategoryID, MAX(t2.UnitPrice) AS C1 FROM northwindef.products t2 GROUP BY t2.CategoryID ) t1 LEFT OUTER JOIN northwindef.categories t3 ON t1.CategoryID = t3.CategoryID

Generated SQL for Oracle DBMS: Generated SQL for Oracle DBMS:

SELECT t3.”CategoryName” AS “Categoryname”, t1.C1 FROM ( SELECT t2.”CategoryID”, MAX(t2.”UnitPrice”) AS C1 FROM NORTHWINDEF.”Products” t2 GROUP BY t2.”CategoryID” ) t1 LEFT OUTER JOIN NORTHWINDEF.”Categories” t3 ON t1.”CategoryID” = t3.”CategoryID”

Generated SQL for MS SQL Server DBMS: Generated SQL for MS SQL Server DBMS:

SELECT [t2].[CategoryName] AS [Category], [t1].[value] AS [Max] FROM ( SELECT MAX([t0].[UnitPrice]) AS [value], [t0].[CategoryID] FROM [dbo].[Products] AS [t0] GROUP BY [t0].[CategoryID] ) AS [t1] LEFT OUTER JOIN [dbo].[Categories] AS [t2] ON [t2].[CategoryID] = [t1].[CategoryID]

Generated SQL for PostgreSQL DBMS: Generated SQL for PostgreSQL DBMS:

SELECT t3.”CategoryName” AS “Categoryname”, t1.”C1″ FROM ( SELECT t2.”CategoryID”, MAX(t2.”UnitPrice”) AS “C1″ FROM public .”Products” t2 GROUP BY t2.”CategoryID” ) t1 LEFT OUTER JOIN public .”Categories” t3 ON t1.”CategoryID” = t3.”CategoryID”

Generated SQL for SQLite DBMS: Generated SQL for SQLite DBMS:

SELECT t3.CategoryName AS Categoryname, t1.C1 AS C1 FROM ( SELECT t2.CategoryID AS CategoryID, MAX(t2.UnitPrice) AS C1 FROM Products t2 GROUP BY t2.CategoryID ) t1 LEFT OUTER JOIN Categories t3 ON (t1.CategoryID = t3.CategoryID) OR ((t1.CategoryID IS NULL ) AND (t3.CategoryID IS NULL ))

Results: Results: The most expensive product in Beverages category costs 263,5

The most expensive product in Condiments category costs 43,9

The most expensive product in Confections category costs 81

Usage of grouping and aggregating functions is easy when LinqConnect is applied.

These simple examples should help one to make some ideas of how to use LinqConnect as a convenient way to work with different databases.

키워드에 대한 정보 101 linq examples

다음은 Bing에서 101 linq examples 주제에 대한 검색 결과입니다. 필요한 경우 더 읽을 수 있습니다.

이 기사는 인터넷의 다양한 출처에서 편집되었습니다. 이 기사가 유용했기를 바랍니다. 이 기사가 유용하다고 생각되면 공유하십시오. 매우 감사합니다!

사람들이 주제에 대해 자주 검색하는 키워드 C# Essentials: Linq for Lists – Sorting, Filtering, and Aggregating Lists Easily

  • .net
  • C#
  • Visual Studio
  • code
  • programming
  • tutorial
  • linq
  • Lists

C# #Essentials: #Linq #for #Lists #- #Sorting, #Filtering, #and #Aggregating #Lists #Easily


YouTube에서 101 linq examples 주제의 다른 동영상 보기

주제에 대한 기사를 시청해 주셔서 감사합니다 C# Essentials: Linq for Lists – Sorting, Filtering, and Aggregating Lists Easily | 101 linq examples, 이 기사가 유용하다고 생각되면 공유하십시오, 매우 감사합니다.

Leave a Comment