Home > Sample chapters > Programming > Visual Studio and .NET

Manipulating Data Using LINQ

Chapter 6 quick reference

To

Do this

Access a non–SQL Server database using LINQ to Entities

Obtain the required database-specific provider to use with ADO.NET.

Create a basic LINQ to Entities query

Combine the from, in, and select keywords to create an expression, and then place the output from this expression into a variable. For example, var CustomerList = from cust in context.Customers select cust obtains a list of all of the customers found in the Customers table of the specified context named context.

Specify that LINQ group the return values in a certain way

Use the group keyword to specify that you want grouping and the by keyword to define which field or expression to use to perform the grouping task. Place the result of the grouping into a variable by using the into keyword.

Specify that LINQ sort the return values in a certain way

Use the orderby keyword to specify that you want the output sorted and include a field or expression to use to perform the sorting task. Control the order of the sort using the ascending or descending keyword.

Output a result set using an in-memory presentation that provides performance benefits during enumeration

Create an output object based on IEnumerable.

Output a result set using a remote presentation that provides flexibility

Create an output object based on IQueryable.

Project specific output values from the query

Use the Select() or SelectMany() methods.

Filter the output to remove undesirable elements

Use the Where() method.

Join two data sources that lack a navigable property

Use the Join() or GroupJoin() method to create an inner, group, or left-outer join.

Create a result set that exhibits one or more specific properties

Use the set-related methods: All(), Any(), Concat(), Contains(), DefaultIfEmpty(), Distinct(), EqualAll(), Except(), Intersect(), and Union().

Change the order in which the rows in a result set appear

Use the ordering-related methods: OrderBy(), OrderByDescending(), ThenBy(), ThenByDescending(), and Reverse().

Define groups of rows containing the same attribute

Use the GroupBy() method.

Define new views of existing data by combining rows

Use the aggregation-related methods: Aggregate(), Average(), Count(), LongCount(), Max(), Min(), and Sum().

Perform type conversion and testing

Use the Convert() (primitive types) and OfType() (entity types). When working with C#, you can also use the is() and as() methods.

Access the rows out of order or remove some rows from the sequence depending on position

Use one of the paging methods: ElementAt(), First(), FirstOrDefault(), Last(), LastOrDefault(), Single(), Skip(), Take(), or TakeWhile().