- LINQ provides an easy way to create and maintain queries for different datasets. Unfortunately, that also makes it easy to create inefficient queries. There's some general tips to keep in mind when creating your queries. An operator that needs to manipulate the entire sequence rather than pulling elements that satisfy criteria will typically require more memory and time to execute. If possible, it is good practice to perform where and select operations first and then perform ordering and grouping operations. That way the more time-intensive process is only iterating over a subset of the data.
If a set of data resulted from a query is needed over and over again but the query takes a long time to execute, consider converting the results with ToList or ToArray. By using the resulting list or array, you can avoid running the query unnecessarily. Having a well organized database that is well indexed will help improve performance since LINQ queries will execute more efficiently. Since LINQ queries have a deferred execution, pay attention to where in your application the query executes or re-executes and when the source data updates.
Often, unexpected results come from forgetting that the data source has been updated. If you need to hold onto the data from a query for later use it is best to convert the results from the query to a list or an array at the time of execution. It's worthwhile noting that LINQ keeps the connection with the database open for the entire time a query is executing. To improve performance, avoid doing any lengthy calculations in a query if it can be done outside of the query after the connection with the database has closed. With these tips you can benefit from LINQ's ease of use while maintaining efficient code.
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