LINQ and C#
LINQ provides many of the common SQL operations, such as join queries, grouping, aggregation, and sorting of results. In addition, it allows you to use the object-oriented features of C# in query expressions and processing, such as hierarchical query results.
Joining
You will often want to search for objects from more than one data source. LINQ provides the join clause that offers the ability to join many data sources, not all of which need be databases. Suppose you have a list of customers containing customer names and email addresses, and a list of customer home addresses. You can use LINQ to combine both lists to produce a list of customers, with access to both their email and home addresses:
from customer in customers
join address in addresses on
customer.Name equals address.Name
...The join condition is specified in the on subclause, similar to SQL, except that the objects joined need not be tables or views in a database. The join class syntax is:
[data source 1] join [data source 2] on [join condition]
Here, we are joining two data sources, customers and addresses, based on the customer name properties in each object. In fact, you can join more than two data sources using a combination of join clauses:
from customer in customers
join address in addresses on
customer.Name equals address.Name
join invoice in invoices on
customer.Id equals invoice.CustomerId
join invoiceItem in invoiceItems on
invoice.Id equals invoiceItem.invoiceIdA LINQ join clause returns a result ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access