Telerik OpenAccess Classic

Telerik OpenAccess ORM Send comments on this topic.
Introduction to LINQ
See Also
Programmer's Guide > OpenAccess ORM Classic (Old API) > Programming With OpenAccess > Query a Data Model > Queries > LINQ > Introduction to LINQ

Glossary Item Box

This documentation article is a legacy resource describing the functionality of the deprecated OpenAccess Classic only. The contemporary documentation of Telerik OpenAccess ORM is available here.

In this chapter we introduce some basic LINQ concepts that are built on technical concepts introduced in the previous chapter. 

Standard Query operators 

Query operators are a set of extension methods that perform operations in the context of LINQ queries. Consider the following example where we filter a list of words to select only those length is greater than four.

C#  Copy Code
string[] words = new string[] { "Hello", "world", "of", "Telerik", "OpenAccess", "ORM" };
           var result = words.Where(w => w.Length > 4).Select(w => w);
           
foreach (string word in result)
           {
               Console.WriteLine(word);
           }
           Console.ReadLine();
VB.NET Copy Code
Dim words As String() = New String() {"Hello", "world", "of", "Telerik", "OpenAccess", "ORM"}
Dim result = words.Where(Function(w As String) w.Length > 4).[Select](Function(w As String) w)
For Each word As String In result
 Console.WriteLine(word)
Next
Console.ReadLine()

As you might have observed, Where is not a method on the System.Array class but still this still works because Where is an extension method defined on the IEnumerable<T> type. Where is defined as follows:

  Copy Code
public static IEnumerable<TSource> Where<TSource>(this 
IEnumerable<TSource> source, Func<TSource, Boolean> predicate);

Query operators can be combined to perform complex operations and queries on enumerations. Several query operators are predefined and cover a wide range of operations. These operators are called standard query operators.

Some examples of standard query operators are Where, Select, GroupBy, Join, Max, Average. Most of these methods operate on sequences, where a sequence is an object whose type implements the IEnumerable <(Of <(T>)>) interface or the IQueryable <(Of <(T>)>) interface.

LINQ Query expressions   

Until now we have been using a syntax based on method calls for our examples. There is another way in which queries can be expressed: using query expressions.

Query operators are extension methods that allow the expression of queries, but you can express the same query using a SQL like syntax. Let us express the query mentioned in the previous section using query expressions.


Using method calling syntax:

C#  Copy Code
var result = words.Where(w => w.Length > 4).Select(w => w);
VB.NET Copy Code
Dim result = words.Where(Function(w As String) w.Length > 4).[Select](Function(w As String) w)

Using query expressions:

 C# Copy Code
var result = from word in words
   where word.Length > 4
   select word;  
VB.NET Copy Code
Dim result = From word In words _
 Where word.Length > 4 _
 Select word

With LINQ, query capabilities are directly integrated into the language, i.e. C# and VB. A query is a first-class construct just like classes, methods, events etc. Query expressions are written in declarative query syntax introduced in C# 3.5.  Complex filtering, ordering and grouping can be performed on various complex data sources using query syntax.

Example: In this example we fetch all Employees objects whose are comming from USA

C# Copy Code
IObjectScope scope = ObjectScopeProvider1.GetNewObjectScope();
           var result = from c in scope.Extent<Employee>() where c.Country == "USA" select c;
           
foreach (Employee emp in result)
           {
               Console.WriteLine(emp.EmployeeID +
" " + emp.Country);
           }
           scope.Dispose();
VB.NET Copy Code
Dim scope As IObjectScope = ObjectScopeProvider1.GetNewObjectScope()
   Dim result = From c In scope.Extent(Of Employee)() _
                Where c.Country = "USA" _
                Select c
   For Each emp As Employee In result
    Console.WriteLine(emp.EmployeeID & " " & emp.Country)
   Next emp
   scope.Dispose()

At compile time the query expression is converted to equivalent Standard Query Operator method calls. Any query expressed using the declarative query syntax can also be expressed by using the method syntax. The method syntax form of the above query would be:

 C# Copy Code
var result = scope.Extent<Employee>().Where(b => b.Country == "USA").Select(b => b);
VB.NET Copy Code
Dim result = scope.Extent(Of Employee)().Where(Function(b) b.Country = "USA").Select(Function(b) b)

For a further details on LINQ query expressions please refer to the MSDN's article Lambda Expressions (C# Programming Guide)

Examples of Standard query operators

Some of the frequently used Standard query operators are explained below.

a) Projection operations – The ‘Select’ method performs a projection.

Example: The following example selects the customers for each order in the database and than displays them.

 C# Copy Code
IObjectScope scope = ObjectScopeProvider1.GetNewObjectScope();
           var result = from c in scope.Extent<Order>() select c.Customer;
           
foreach (Customer cst in result)
           {
               Console.WriteLine(cst.Address+
" "+cst.City);
           }
           scope.Dispose();
VB.NET Copy Code
Dim scope As IObjectScope = ObjectScopeProvider1.GetNewObjectScope()
Dim result = From c In scope.Extent(Of Order)() _
 Where c.Customer.CustomerID = "ALFKI" _
 Select c.Customer
For Each cst As Customer In result
 Console.WriteLine(cst.Address + " " + cst.City)
Next
scope.Dispose()

For more information please refer to LINQ to SQL MSDN article. 

b) Filter operations‘Where’ and ‘OfType’ are methods that perform filtering.

The standard query operator method ‘Where’, selects values based on a predicate function.

Example: In this example we retrieve all products with unit price more than 4

C#  Copy Code
var result = from c in scope.Extent<Product>() where c.UnitPrice > 4 select c;

 

VB.NET Copy Code
Dim result = From c In scope.Extent(Of Product)() _
 Where c.UnitPrice > 4 _
 Select c

 

c) Sorting operations – ‘OrderBy’ and ‘OrderByDescending’ are commonly used sorting methods.

 

Example: Following example sorts the products objects by the unit price.

C#  Copy Code
var result = from c in scope.Extent<Product>() orderby c.UnitPrice select c;

 

VB.NET Copy Code
Dim result = From c In scope.Extent(Of Product)() _
 Order By c.UnitPrice _
 Select c

 

orderby p.UnitPrice descending will sort the result in descending order.

d) Grouping operations – ‘GroupBy’ is a standard query operator method for grouping.

Example: This example fetches all Order objects grouped by the Product name

 C# Copy Code
var result = from o in objectScope.Extent<Order>()
            group o by o.Employee.FirstName;
VB.NET Copy Code
Dim result = From o In objectScope.Extent(Of Order)() _
 Group o By o.Employee.FirstName

 

Note: Currently this does not work.

 

LINQ in detail

Further detailed description of LINQ and its capabilities can be found in MSDN.

               

Advanced queries

Querying collections

Queries on collection fields within persistent instances can be written simply by referencing the collection field as you would normally do.

Example: In the following example we retrieve all Customers who have placed an order after a particular date.

C#  Copy Code
DateTime myDate = DateTime.Parse("1998/1/1");
           var result = from c
in scope.Extent<Order>() where c.OrderDate > myDate select c.Customer;

 

VB.NET Copy Code
Dim myDate As DateTime = DateTime.Parse("1998/1/1")
Dim result = From c In scope.Extent(Of Order)() _
 Where c.OrderDate > myDate _
 Select c.Customer

 

Exists operator

Using LINQ queries you can query a collection to determine whether any element in the collection satisfies a particular condition.

Example: In this example we retrieve all Employees who have came from region containing Eastern in its description

C#  Copy Code
var result = from b in scope.Extent<Employee>()
                        where b.EmployeeTerritories.Any(o => o.Region.RegionDescription ==
"Eastern")
                        select b;

VB.NET Copy Code
Dim result = From b In scope.Extent(Of Employee)() _
             Where b.EmployeeTerritories.Any(Function(o) o.Region.RegionDescription = "Eastern") _
             Select b

 

Cast operator

Occasionally, you may find it necessary to use a cast operation in a query. Casting in LINQ is same as casting in your object oriented programming language. You can cast an object only to a related class, i.e., to a super-class (base class) or to a sub-class (a derived class).

 

Example: This query returns all the instances of Book whose page count is greater than 460.

Here we cast the Product reference to the Book type.3

 

 

C#  Copy Code
var result = from o in objectScope.Extent<Order>()
             where ((Book)o.Product).Pages > 460
             select o; 
VB.NET Copy Code
Dim result = From o In objectScope.Extent(Of Order)() _
             Where (CType(o.Product, Book)).Pages > 460 _
             Select o
NOTE: Using the cast operator on the candidate variable (in this case, the Order type variable ‘o’) is not yet supported.

See Also