Databases Reference
In-Depth Information
property name. LINQ also includes the ascending keyword, but like its counterpart in
SQL, is rarely used because it is the default.
Multiple properties can be specified as well, separated by comas. If the descending
keyword is used with multiple columns specified in the orderby list, it applies only to the
property on its immediate left, such as the UnitsOnOrder in the next example:
var query = from p in context.Products
orderby p.UnitsInStock, p.UnitsOnOrder descending
select p;
Grouping
The group..by LINQ operator can be used to group query results by one or more property
values. For example, we could get a list of Products grouped by their Suppliers with the
LINQ query shown here:
var query = from p in context.Products
group p by p.SupplierID into g
select new{
Supplier = g.FirstOrDefault().Supplier,
Products = g
};
foreach (var group in query)
{
Console.WriteLine(“Supplier: “ + group.Supplier.CompanyName);
foreach (var product in group.Products)
Console.WriteLine(“\t” + product.ProductName);
}
The group by operator returns an object that implements the IGrouping<TKey, TElement>
interface, where TKey is the type of the property used for grouping, such as the SupplierID
in our example, and TElement is the type of entity whose instances are being grouped,
which in our example is the Product entity. An IGrouping<TKey , TElement> object is also
an IEnumerable<TElement> , so you can access all elements in a group simply by enumerat-
ing it. Although it would be possible to have the query return the IGrouping objects
directly, it is common to have it return an anonymous type that makes the results easier
to understand. In this example, the code “selects” an anonymous type where Supplier
property contains a Supplier instance and the Products property contains all of the
Product instances offered by that supplier.
Joins
Although LINQ makes many queries that normally require a join in SQL possible with
simple traversal of the entity relationships, it also supports joins where the explicit rela-
tionships might not exist in the data model. For example, although we have address infor-
mation for Customers and Suppliers defined in the Northwind data model, there is no
explicit relationship connecting them. To cross-reference customers and suppliers located
in the same city, we would need to perform a join, as shown here:
 
Search WWH ::




Custom Search