From 84837332b4f4369caf0c9ecf060e5e42433d8be2 Mon Sep 17 00:00:00 2001 From: zHaytam Date: Sat, 16 May 2020 20:10:03 +0000 Subject: [PATCH] Initial commit --- .gitattributes | 2 + .gitignore | 353 ++++++++++++++++++ .../DynamicExpressions.Benchmarks.csproj | 17 + DynamicExpressions.Benchmarks/Entry.cs | 22 ++ DynamicExpressions.Benchmarks/Filter.cs | 45 +++ .../NestedOrderByDescending.cs | 52 +++ .../OrderByDescending.cs | 52 +++ DynamicExpressions.Benchmarks/Program.cs | 46 +++ DynamicExpressions.Benchmarks/SubEntry.cs | 7 + DynamicExpressions.sln | 31 ++ DynamicExpressions/DynamicExpressions.cs | 67 ++++ DynamicExpressions/DynamicExpressions.csproj | 9 + DynamicExpressions/DynamicFilterBuilder.cs | 64 ++++ DynamicExpressions/ExpressionExtensions.cs | 22 ++ DynamicExpressions/FilterOperator.cs | 13 + LICENSE | 21 ++ README.md | 2 + 17 files changed, 825 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 DynamicExpressions.Benchmarks/DynamicExpressions.Benchmarks.csproj create mode 100644 DynamicExpressions.Benchmarks/Entry.cs create mode 100644 DynamicExpressions.Benchmarks/Filter.cs create mode 100644 DynamicExpressions.Benchmarks/NestedOrderByDescending.cs create mode 100644 DynamicExpressions.Benchmarks/OrderByDescending.cs create mode 100644 DynamicExpressions.Benchmarks/Program.cs create mode 100644 DynamicExpressions.Benchmarks/SubEntry.cs create mode 100644 DynamicExpressions.sln create mode 100644 DynamicExpressions/DynamicExpressions.cs create mode 100644 DynamicExpressions/DynamicExpressions.csproj create mode 100644 DynamicExpressions/DynamicFilterBuilder.cs create mode 100644 DynamicExpressions/ExpressionExtensions.cs create mode 100644 DynamicExpressions/FilterOperator.cs create mode 100644 LICENSE create mode 100644 README.md diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e645270 --- /dev/null +++ b/.gitignore @@ -0,0 +1,353 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ diff --git a/DynamicExpressions.Benchmarks/DynamicExpressions.Benchmarks.csproj b/DynamicExpressions.Benchmarks/DynamicExpressions.Benchmarks.csproj new file mode 100644 index 0000000..f888232 --- /dev/null +++ b/DynamicExpressions.Benchmarks/DynamicExpressions.Benchmarks.csproj @@ -0,0 +1,17 @@ + + + + Exe + netcoreapp3.1 + DynamicExpressions.Benchmarks + + + + + + + + + + + diff --git a/DynamicExpressions.Benchmarks/Entry.cs b/DynamicExpressions.Benchmarks/Entry.cs new file mode 100644 index 0000000..918b5b5 --- /dev/null +++ b/DynamicExpressions.Benchmarks/Entry.cs @@ -0,0 +1,22 @@ +namespace DynamicExpressions.Benchmarks +{ + public class Entry + { + + public string Title { get; set; } + public int Number { get; set; } + public SubEntry SubEntry { get; set; } + + public Entry(string title, int number) + { + Title = title; + Number = number; + } + + public Entry(string title, int number, SubEntry subEntry) : this(title, number) + { + SubEntry = subEntry; + } + + } +} diff --git a/DynamicExpressions.Benchmarks/Filter.cs b/DynamicExpressions.Benchmarks/Filter.cs new file mode 100644 index 0000000..77a9bcd --- /dev/null +++ b/DynamicExpressions.Benchmarks/Filter.cs @@ -0,0 +1,45 @@ +using BenchmarkDotNet.Attributes; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace DynamicExpressions.Benchmarks +{ + [MemoryDiagnoser] + public class Filter + { + private readonly List _entries; + + public Filter() + { + _entries = new List(); + for (int i = 0; i < 5000; i++) + { + _entries.Add(new Entry($"Title {i}", i, new SubEntry($"SubTitle {i}", i))); + } + } + + [Benchmark(Baseline = true)] + public List ManualLambda() + { + return _entries.AsQueryable().Where(e => + e.Title.Contains("Title") + || (e.Title.EndsWith("1") && e.Number == 1) + || (e.Title.EndsWith("2") && e.Number == 2)).ToList(); + } + + [Benchmark] + public List GeneratedLambda() + { + var predicate = new DynamicFilterBuilder() + .And("Title", FilterOperator.Contains, "Title") + .Or(b => b.And("Title", FilterOperator.EndsWith, "1").And("Number", FilterOperator.Equals, 1)) + .Or(b => b.And("Title", FilterOperator.EndsWith, "2").And("Number", FilterOperator.Equals, 2)) + .Build(); + + return _entries.AsQueryable().Where(predicate).ToList(); + } + + } +} diff --git a/DynamicExpressions.Benchmarks/NestedOrderByDescending.cs b/DynamicExpressions.Benchmarks/NestedOrderByDescending.cs new file mode 100644 index 0000000..ddb960b --- /dev/null +++ b/DynamicExpressions.Benchmarks/NestedOrderByDescending.cs @@ -0,0 +1,52 @@ +using BenchmarkDotNet.Attributes; +using System.Collections.Generic; +using System.Linq; + +namespace DynamicExpressions.Benchmarks +{ + [MemoryDiagnoser] + public class NestedOrderByDescending + { + + private readonly List _entries; + + public NestedOrderByDescending() + { + _entries = new List(); + for (int i = 0; i < 5000; i++) + { + _entries.Add(new Entry($"Title {i}", i, new SubEntry($"SubTitle {i}", i))); + } + } + + [Benchmark(Baseline = true)] + public List> SearchTitle() + { + var result = new List>(); + + for (int i = 0; i <= 500; i++) + { + var orderedEntries = _entries.AsQueryable().OrderByDescending(p => (object)p.SubEntry.Number).ToList(); + result.Add(orderedEntries); + } + + return result; + } + + [Benchmark] + public List> SearchTitleDynamicallyWithoutCache() + { + var result = new List>(); + + for (int i = 0; i <= 500; i++) + { + var expr = DynamicExpressions.GetPropertyGetter("SubEntry.Number"); + var orderedEntries = _entries.AsQueryable().OrderByDescending(expr).ToList(); + result.Add(orderedEntries); + } + + return result; + } + + } +} diff --git a/DynamicExpressions.Benchmarks/OrderByDescending.cs b/DynamicExpressions.Benchmarks/OrderByDescending.cs new file mode 100644 index 0000000..3d3e5c0 --- /dev/null +++ b/DynamicExpressions.Benchmarks/OrderByDescending.cs @@ -0,0 +1,52 @@ +using BenchmarkDotNet.Attributes; +using System.Collections.Generic; +using System.Linq; + +namespace DynamicExpressions.Benchmarks +{ + [MemoryDiagnoser] + public class OrderByDescending + { + + private readonly List _entries; + + public OrderByDescending() + { + _entries = new List(); + for (int i = 0; i < 5000; i++) + { + _entries.Add(new Entry($"Title {i}", i)); + } + } + + [Benchmark(Baseline = true)] + public List> SearchTitle() + { + var result = new List>(); + + for (int i = 0; i <= 500; i++) + { + var orderedEntries = _entries.AsQueryable().OrderByDescending(p => p.Title).ToList(); + result.Add(orderedEntries); + } + + return result; + } + + [Benchmark] + public List> SearchTitleDynamicallyWithoutCache() + { + var result = new List>(); + + for (int i = 0; i <= 500; i++) + { + var expr = DynamicExpressions.GetPropertyGetter("Title"); + var orderedEntries = _entries.AsQueryable().OrderByDescending(expr).ToList(); + result.Add(orderedEntries); + } + + return result; + } + + } +} diff --git a/DynamicExpressions.Benchmarks/Program.cs b/DynamicExpressions.Benchmarks/Program.cs new file mode 100644 index 0000000..2238322 --- /dev/null +++ b/DynamicExpressions.Benchmarks/Program.cs @@ -0,0 +1,46 @@ +using BenchmarkDotNet.Running; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; + +namespace DynamicExpressions.Benchmarks +{ + internal class Program + { + private static void Main(string[] args) + { + var entries = new List + { + new Entry("Title 1", 1, new SubEntry("SubTitle 1", 1)), + new Entry("Title 2", 2, new SubEntry("SubTitle 2", 2)) + }; + + //Expression> expr = DynamicExpressions.GetPropertyGetter("SubEntry.Title"); + //var result = entries.AsQueryable().OrderByDescending(expr).ToList(); + + //var expr = DynamicExpressions.GetPredicate("SubEntry.Title", FilterOperator.Equals, "SubTitle 2"); + //var entry = entries.AsQueryable().Where(expr).ToList(); + + + //var predicate = DynamicFilterBuilder + // .StartWith("Title", FilterOperator.Equals, "Title 1") + // .And("Number", FilterOperator.Equals, 2) + // .Build(); + + //var entry = entries.AsQueryable().FirstOrDefault(predicate); + + Func x = e => (e.Title.EndsWith("1") && e.Number == 1) || (e.Title.EndsWith("2") && e.Number == 2); + var predicate = new DynamicFilterBuilder() + .And("Title", FilterOperator.Contains, "Title") + .Or(b => b.And("Title", FilterOperator.EndsWith, "1").And("Number", FilterOperator.Equals, 1)) + .Or(b => b.And("Title", FilterOperator.EndsWith, "2").And("Number", FilterOperator.Equals, 2)) + .Build(); + + var e = entries.AsQueryable().Where(predicate).ToList(); + + BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args); + } + + } +} diff --git a/DynamicExpressions.Benchmarks/SubEntry.cs b/DynamicExpressions.Benchmarks/SubEntry.cs new file mode 100644 index 0000000..2d75519 --- /dev/null +++ b/DynamicExpressions.Benchmarks/SubEntry.cs @@ -0,0 +1,7 @@ +namespace DynamicExpressions.Benchmarks +{ + public class SubEntry : Entry + { + public SubEntry(string title, int number) : base(title, number) { } + } +} diff --git a/DynamicExpressions.sln b/DynamicExpressions.sln new file mode 100644 index 0000000..846dfda --- /dev/null +++ b/DynamicExpressions.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30028.174 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DynamicExpressions", "DynamicExpressions\DynamicExpressions.csproj", "{0A62B8FB-770A-4AA6-BEC6-B966537DB69F}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DynamicExpressions.Benchmarks", "DynamicExpressions.Benchmarks\DynamicExpressions.Benchmarks.csproj", "{B0EC7669-9F45-4CE1-B53C-917BC5480D5C}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0A62B8FB-770A-4AA6-BEC6-B966537DB69F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0A62B8FB-770A-4AA6-BEC6-B966537DB69F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0A62B8FB-770A-4AA6-BEC6-B966537DB69F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0A62B8FB-770A-4AA6-BEC6-B966537DB69F}.Release|Any CPU.Build.0 = Release|Any CPU + {B0EC7669-9F45-4CE1-B53C-917BC5480D5C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B0EC7669-9F45-4CE1-B53C-917BC5480D5C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B0EC7669-9F45-4CE1-B53C-917BC5480D5C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B0EC7669-9F45-4CE1-B53C-917BC5480D5C}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {D2345DFF-7DDB-4859-B3BE-FDE76FAD7109} + EndGlobalSection +EndGlobal diff --git a/DynamicExpressions/DynamicExpressions.cs b/DynamicExpressions/DynamicExpressions.cs new file mode 100644 index 0000000..0a44a2f --- /dev/null +++ b/DynamicExpressions/DynamicExpressions.cs @@ -0,0 +1,67 @@ +using System; +using System.Linq.Expressions; +using System.Reflection; + +namespace DynamicExpressions +{ + public static class DynamicExpressions + { + private static readonly MethodInfo _containsMethod = typeof(string).GetMethod("Contains" + , new Type[] { typeof(string) }); + + private static readonly MethodInfo _startsWithMethod + = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) }); + + private static readonly MethodInfo _endsWithMethod + = typeof(string).GetMethod("EndsWith", new Type[] { typeof(string) }); + + public static Expression> GetPropertyGetter(string property) + { + if (property == null) + throw new ArgumentNullException(nameof(property)); + + var param = Expression.Parameter(typeof(TEntity)); + var prop = param.GetNestedProperty(property); + var convertedProp = Expression.Convert(prop, typeof(object)); + return Expression.Lambda>(convertedProp, param); + } + + public static Func GetCompiledPropertyGetter(string property) + { + return GetPropertyGetter(property).Compile(); + } + + public static Expression> GetPredicate(string property, FilterOperator op, object value) + { + var param = Expression.Parameter(typeof(TEntity)); + return Expression.Lambda>(GetPredicate(param, property, op, value), param); + } + + public static Func GetCompiledPredicate(string property, FilterOperator op, object value) + { + return GetPredicate(property, op, value).Compile(); + } + + internal static Expression GetPredicate(ParameterExpression param, string property, FilterOperator op, object value) + { + var constant = Expression.Constant(value); + var prop = param.GetNestedProperty(property); + return CreateFilter(prop, op, constant); + } + + private static Expression CreateFilter(MemberExpression prop, FilterOperator op, ConstantExpression constant) + { + return op switch + { + FilterOperator.Equals => Expression.Equal(prop, constant), + FilterOperator.GreaterThan => Expression.GreaterThan(prop, constant), + FilterOperator.LessThan => Expression.LessThan(prop, constant), + FilterOperator.Contains => Expression.Call(prop, _containsMethod, constant), + FilterOperator.StartsWith => Expression.Call(prop, _startsWithMethod, constant), + FilterOperator.EndsWith => Expression.Call(prop, _endsWithMethod, constant), + FilterOperator.DoesntEqual => Expression.NotEqual(prop, constant), + _ => throw new NotImplementedException(), + }; + } + } +} \ No newline at end of file diff --git a/DynamicExpressions/DynamicExpressions.csproj b/DynamicExpressions/DynamicExpressions.csproj new file mode 100644 index 0000000..5793b87 --- /dev/null +++ b/DynamicExpressions/DynamicExpressions.csproj @@ -0,0 +1,9 @@ + + + + netstandard2.1 + DynamicExpressions + DynamicExpressions + + + diff --git a/DynamicExpressions/DynamicFilterBuilder.cs b/DynamicExpressions/DynamicFilterBuilder.cs new file mode 100644 index 0000000..4f610b8 --- /dev/null +++ b/DynamicExpressions/DynamicFilterBuilder.cs @@ -0,0 +1,64 @@ +using System; +using System.Linq.Expressions; + +namespace DynamicExpressions +{ + public class DynamicFilterBuilder + { + private readonly ParameterExpression _param; + + public DynamicFilterBuilder() : this(Expression.Parameter(typeof(TEntity))) { } + + DynamicFilterBuilder(ParameterExpression param) + { + _param = param; + } + + private Expression Expression { get; set; } + + public DynamicFilterBuilder And(string property, FilterOperator op, object value) + { + var newExpr = DynamicExpressions.GetPredicate(_param, property, op, value); + Expression = Expression == null ? newExpr : Expression.AndAlso(Expression, newExpr); + return this; + } + + public DynamicFilterBuilder And(Action> action) + { + var builder = new DynamicFilterBuilder(_param); + action(builder); + + if (builder.Expression == null) + throw new Exception("Empty builder"); + + Expression = Expression == null ? builder.Expression : Expression.AndAlso(Expression, builder.Expression); + return this; + } + + public DynamicFilterBuilder Or(string property, FilterOperator op, object value) + { + var newExpr = DynamicExpressions.GetPredicate(_param, property, op, value); + Expression = Expression == null ? newExpr : Expression.OrElse(Expression, newExpr); + return this; + } + + public DynamicFilterBuilder Or(Action> action) + { + var builder = new DynamicFilterBuilder(_param); + action(builder); + + if (builder.Expression == null) + throw new Exception("Empty builder"); + + Expression = Expression == null ? builder.Expression : Expression.OrElse(Expression, builder.Expression); + return this; + } + + public Expression> Build() + { + return Expression.Lambda>(Expression, _param); + } + + public Func Compile() => Build().Compile(); + } +} diff --git a/DynamicExpressions/ExpressionExtensions.cs b/DynamicExpressions/ExpressionExtensions.cs new file mode 100644 index 0000000..8d75e80 --- /dev/null +++ b/DynamicExpressions/ExpressionExtensions.cs @@ -0,0 +1,22 @@ +using System.Linq.Expressions; + +namespace DynamicExpressions +{ + public static class ExpressionExtensions + { + + public static MemberExpression GetNestedProperty(this Expression param, string property) + { + var propNames = property.Split('.'); + var propExpr = Expression.Property(param, propNames[0]); + + for (int i = 1; i < propNames.Length; i++) + { + propExpr = Expression.Property(propExpr, propNames[i]); + } + + return propExpr; + } + + } +} diff --git a/DynamicExpressions/FilterOperator.cs b/DynamicExpressions/FilterOperator.cs new file mode 100644 index 0000000..fcb792a --- /dev/null +++ b/DynamicExpressions/FilterOperator.cs @@ -0,0 +1,13 @@ +namespace DynamicExpressions +{ + public enum FilterOperator + { + Equals, + DoesntEqual, + GreaterThan, + LessThan, + Contains, + StartsWith, + EndsWith + } +} diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..446952b --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 zHaytam + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..9a10a13 --- /dev/null +++ b/README.md @@ -0,0 +1,2 @@ +# DynamicExpressions + A dynamic expression builder that can be used to dynamically sort and/or filter LINQ/EF queries