Sam.DynamicPredicate 1.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Sam.DynamicPredicate --version 1.0.0                
NuGet\Install-Package Sam.DynamicPredicate -Version 1.0.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Sam.DynamicPredicate" Version="1.0.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Sam.DynamicPredicate --version 1.0.0                
#r "nuget: Sam.DynamicPredicate, 1.0.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Sam.DynamicPredicate as a Cake Addin
#addin nuget:?package=Sam.DynamicPredicate&version=1.0.0

// Install Sam.DynamicPredicate as a Cake Tool
#tool nuget:?package=Sam.DynamicPredicate&version=1.0.0                

Dynamic Filtering

In software development, one of the critical needs is filtering data based on various and dynamic conditions. The Sam.DynamicPredicate package provides developers with a powerful tool for this purpose. This article explores the Sam.DynamicPredicate package, how to use it, and the benefits it offers for filtering data using LINQ.

Introduction to the Sam.DynamicPredicate Package

The Sam.DynamicPredicate package allows you to create LINQ queries dynamically based on predicate strings. By leveraging .NET's Reflection and Expression Trees, this package converts filter conditions into executable LINQ expressions.

How to Use the Sam.DynamicPredicate Package

To use this package, You should install Sam.DynamicPredicate with NuGet using the following command

Install-Package Sam.DynamicPredicate

Or via the .NET Core command line interface:

dotnet add package Sam.DynamicPredicate

Example Usage in an ASP.NET Core Controller

After installing the package, you can use it to dynamically build LINQ queries based on string predicates. Below is an example within an ASP.NET Core controller (ProductController):

[ApiController]
[Route("api/[controller]/[action]")]
public class ProductController(ApplicationDbContext applicationDbContext, ILogger<Product> logger) : ControllerBase
{
    [HttpGet]
    public async Task<object> Get()
    {
        var query = applicationDbContext.Products.AsQueryable();

        query = query.Where("Id == 1 || Id == 2 || ( Name StartsWith Pro && Price >= 10000 )");

        var sqlQuery = query.ToQueryString();
        logger.LogInformation("query -> " + sqlQuery);

        return new
        {
            SqlQuery = sqlQuery,
            Data= await query.ToListAsync()
        };
    }
}

Explanation

  1. Install Package: Use dotnet add package command to add Sam.DynamicPredicate to your project dependencies.
  2. Controller Setup: ProductController is set up as an ASP.NET Core controller handling HTTP GET requests.
  3. Query Building: Inside the Get() method, _context.Products.AsQueryable() initializes a queryable collection of products from your database.
  4. Dynamic Query: query.Where("Id == 1 || Id == 2 || (Name.StartsWith("Pro") && Price >= 10000)") demonstrates the use of Sam.DynamicPredicate. This method dynamically constructs a LINQ query based on the provided string predicate.
  5. Logging: query.ToQueryString() converts the LINQ query to a SQL string, logged using _logger.LogInformation().
  6. Return: The method returns an anonymous object containing the SQL query (SqlQuery) and the asynchronously fetched data (Data) converted to JSON.
The value of the sqlQuery variable in this example is as follows
SELECT [p].[Id], [p].[BarCode], [p].[Name], [p].[Price]
FROM [Products] AS [p]
WHERE [p].[Id] IN (CAST(1 AS bigint), CAST(2 AS bigint)) OR ([p].[Name] LIKE N'Pro%' AND [p].[Price] >= 10000.0E0)

Note that the where method, which has a string input, is located in the Sam.DynamicPredicate namespace.

A guide to making string filters

Benefits of Using the Sam.DynamicPredicate Package

  1. Dynamic and Adjustable Filters
    • One of the biggest advantages of this package is the ability to define dynamic filters based on changing needs. You can input various conditions as strings and easily apply the filters.
  2. Reduced Code Complexity
    • Using this package, your code becomes cleaner and more manageable. There is no need to write complex queries for every condition, and you can use a uniform structure for all conditions.
  3. Improved Readability and Maintenance
    • Utilizing predicate strings instead of combining multiple LINQ expressions enhances code readability. This approach simplifies maintenance and makes it easy to modify filter conditions.
  4. High Flexibility
    • The Sam.DynamicPredicate package supports various types of conditions, including simple comparisons, text comparisons, and more complex conditions using logical operators.
  5. High Performance

    • With this package, the generated queries are optimized and directly translated into equivalent SQL statements, ensuring high performance during execution.

Open Source Project Availability

The Sam.DynamicPredicate package is an open-source project available on GitHub. You can view the source code and contribute to its development or report issues.

GitHub Repository: Sam.DynamicPredicate on GitHub

Issues and Contributions: Feel free to explore the codebase, report any issues, or suggest improvements through GitHub Issues.

This transparency and accessibility ensure that the project is community-driven and welcomes contributions, fostering continuous improvement and reliability.

Conclusion

The Sam.DynamicPredicate package is a powerful and practical tool for dynamic filtering in LINQ. By providing capabilities to convert predicate strings into LINQ expressions, this package helps developers create queries easily and with high flexibility. Using this package, you can have cleaner, more readable, and maintainable code, improving the performance of your applications.

Using the Sam.DynamicPredicate package allows you to quickly and dynamically respond to new filter conditions without rewriting code, thereby increasing your productivity.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 2.1

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.0.1 103 6/17/2024
1.0.0 93 6/16/2024