- By combining basic queries together I can create more complicated queries. This is called chaining. Imagine that I want the last names of customers from Oregon. Ordered from the biggest spender to the one who spent the least. I already know how to do this with three separate queries. I first want to filter the customers are in turn those that reside in Oregon. Then, I want to order the results from the state query by the price property value for each customer element. And finally, I take the results from the price query and select just the last names of the customers.
Now, I create the four H statement to execute all the queries I just created. When I call the name query it will in turn call the price query which in turn will call the state query. When I run the program I see that I have the last names of the customers who reside in Oregon, ordered by the amount they have spent. This is one way to chain together multiple queries. But one of the really powerful things about Link is that you can chain all these together in one query without having to create temporary sequences in between queries.
I'll begin to rewrite that query by naming it chainQuery. First, I filter my customers for those in Oregon. Then I order them by the price property. And finally I select the last name property to be in the final return of sequence.
This does exactly the same thing as the three separate queries but this is significantly easier to read. When I execute this, the results of one query will be passed on to the next query to be processed in the order specified. So now I run my code. And you see I get the same names of customers from Oregon ordered by how much they spent. Chaining and Link gives us the ability to combine the basic queries into larger, more complicated queries. This reduces the number of queries I have to define and allows me to create complex queries that are easy to read and understand.
In LINQ with C# Essential Training, engineer Olivia Chiu introduces techniques for querying, updating, and transforming data with LINQ. She covers standard queries—such as finding overlaps in two datasets and creating hierarchies—as well as complex chained queries. She also shows how to group and join LINQ queries with lambda expressions, and use LINQ to query SQL databases and XML documents. Last but not least, Olivia provides tips for optimizing the performance of your queries.
- Creating and executing a LINQ query
- Returning results
- Changing the data source type
- Performing standard queries
- Working with lambda expressions
- Chaining and complex queries
- Querying SQL and XML
- Performing tree queries
- Using sequences, elements, and scalars
- Allocating memory