LINQ (Language-Integrated Query) is a part of the C# and Visual Basic .NET languages that lets you “query” data collections, databases and XML documents (and anything else that you write a custom LINQ provider for). The syntax will feel very familiar to anyone who has experience writing SQL queries. SQL allows for the creation and execution of dynamic queries based on data pulled from a database. This dynamic query generation affords a powerful flexibility over regular SQL statements. Similarly, with LINQ there are times when you don’t know how you want to query your data until run time. You can use the standard LINQ library to build dynamic queries, but it can be a huge pain. Instead, I recommend the System.Linq.Dynamic
library for building dynamic LINQ queries.
Example non-dynamic LINQ query:
static void Main(string[] args) { List<string> Names = new List<string> { "Phil", "Jessica", "James", "Yolanda" }; var nameQuery = from name in Names let namelc = name.ToLower() where namelc[0] == 'j' select name; foreach (var name in nameQuery) { Console.WriteLine(name); } Console.ReadKey(); } |
Jessica James |
The System.Linq.Dynamic
library does not ship with Visual Studio. Instead, download it through the NuGet Package Manager. You can use the “Manage NuGet Packages” GUI interface by searching for “Dynamic Linq”, or the Package Manager Console:
Install-Package System.Linq.Dynamic |
Once installed and referenced in a project, you’ll have access to overloaded query methods that allow you to use strings instead of static values to query your data. Make sure to add a using System.Linq.Dynamic
directive to make the extra overloads available.
Example dynamic LINQ query:
static void Main(string[] args) { List<string> Names = new List<string> { "Phil", "Jessica", "James", "Yolanda" }; string variableWhere = "it[0].ToString().ToLower() == \"j\""; string variableSelect = "it"; var valueQuery = Names .Where(variableWhere) .Select(variableSelect); foreach (var value in valueQuery) Console.WriteLine(value); Console.ReadKey(); } |
Jessica James |
Dynamic LINQ queries allow you to define queries at run-time. The query components just need to be strings, which can be loaded from configuration files, a database, user input or any other source that you like.