text
stringlengths
9
39.2M
dir
stringlengths
25
226
lang
stringclasses
163 values
created_date
timestamp[s]
updated_date
timestamp[s]
repo_name
stringclasses
751 values
repo_full_name
stringclasses
752 values
star
int64
1.01k
183k
len_tokens
int64
1
18.5M
```smalltalk using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EntityFramework.DynamicLinq.Tests")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3577bad5-cd9b-4b8f-b326-df11836e9e1f")] ```
/content/code_sandbox/test/EntityFramework.DynamicLinq.Tests/Properties/AssemblyInfo.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
171
```xml <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <Authors>Stef Heyenrath</Authors> <TargetFrameworks>net461;net8.0</TargetFrameworks> <DebugType>full</DebugType> <DefineConstants>EF;NET461</DefineConstants> <AssemblyName>EntityFramework.DynamicLinq.Tests</AssemblyName> <PackageId>EntityFramework.DynamicLinq.Tests</PackageId> <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> <ProjectGuid>{BF97CB1B-5043-4256-8F42-CF3A4F3863BE}</ProjectGuid> <SignAssembly>True</SignAssembly> <AssemblyOriginatorKeyFile>../../src/System.Linq.Dynamic.Core/System.Linq.Dynamic.Core.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <ItemGroup> <Compile Include="..\System.Linq.Dynamic.Core.Tests\QueryableTests.cs" /> <Compile Include="..\System.Linq.Dynamic.Core.Tests\QueryableTests.*.cs" /> <Compile Include="..\System.Linq.Dynamic.Core.Tests\EntitiesTests.cs" /> <Compile Include="..\System.Linq.Dynamic.Core.Tests\EntitiesTests.*.cs" /> <Compile Include="..\System.Linq.Dynamic.Core.Tests\Entities\*.cs" /> <Compile Include="..\System.Linq.Dynamic.Core.Tests\TestHelpers\*.cs" /> <Compile Include="..\System.Linq.Dynamic.Core.Tests\Helpers\*.cs" /> <Compile Include="..\System.Linq.Dynamic.Core.Tests\Helpers\*\*.cs" /> <Compile Include="..\System.Linq.Dynamic.Core.Tests\D*.cs" /> <Compile Include="..\System.Linq.Dynamic.Core.Tests\TestClasses\*.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\src\System.Linq.Dynamic.Core\System.Linq.Dynamic.Core.csproj" /> <ProjectReference Include="..\..\src\EntityFramework.DynamicLinq\EntityFramework.DynamicLinq.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="coverlet.msbuild" Version="6.0.2"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> <PackageReference Include="coverlet.collector" Version="6.0.2"> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> <PackageReference Include="FluentAssertions" Version="5.10.3" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> <PackageReference Include="NodaTime" Version="2.4.7" /> <PackageReference Include="Testcontainers.MsSql" Version="3.9.0" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> <PackageReference Include="Linq.PropertyTranslator.Core" Version="1.0.5" /> <PackageReference Include="QueryInterceptor.Core" Version="1.0.9" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="NFluent" Version="2.8.0" /> <PackageReference Include="Moq" Version="4.13.1" /> </ItemGroup> <ItemGroup Condition=" '$(TargetFramework)' == 'net461' "> <Reference Include="System" /> <Reference Include="Microsoft.CSharp" /> <PackageReference Include="Microsoft.AspNet.Identity.EntityFramework" Version="2.2.1" /> <PackageReference Include="LinqKit.EntityFramework" Version="1.1.15" /> </ItemGroup> <ItemGroup Condition=" '$(TargetFramework)' == 'net8.0' "> <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.0" /> <PackageReference Include="LinqKit.Microsoft.EntityFrameworkCore" Version="8.1.5" /> </ItemGroup> <PropertyGroup Condition=" '$(TargetFramework)' == 'net8.0' "> <DefineConstants>$(DefineConstants);AspNetCoreIdentity</DefineConstants> </PropertyGroup> </Project> ```
/content/code_sandbox/test/EntityFramework.DynamicLinq.Tests/EntityFramework.DynamicLinq.Tests.csproj
xml
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
1,027
```xml <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net6.0</TargetFramework> <AssemblyName>System.Linq.Dynamic.Core.Tests</AssemblyName> <DebugType>full</DebugType> <SignAssembly>True</SignAssembly> <AssemblyOriginatorKeyFile>../../src/System.Linq.Dynamic.Core/System.Linq.Dynamic.Core.snk</AssemblyOriginatorKeyFile> <IsPackable>false</IsPackable> <DefineConstants>$(DefineConstants);NETCOREAPP;EFCORE;EFCORE_3X;NETCOREAPP3_1;AspNetCoreIdentity</DefineConstants> </PropertyGroup> <ItemGroup> <PackageReference Include="coverlet.msbuild" Version="6.0.2"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" /> <PackageReference Include="xunit" Version="2.4.2" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.5"> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> <PackageReference Include="coverlet.collector" Version="6.0.2"> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> <PackageReference Include="Linq.PropertyTranslator.Core" Version="1.0.5" /> <PackageReference Include="QueryInterceptor.Core" Version="1.0.9" /> <PackageReference Include="NFluent" Version="2.8.0" /> <PackageReference Include="Moq" Version="4.18.2" /> <PackageReference Include="FluentAssertions" Version="6.8.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.0" /> <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="6.0.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="6.0.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.0" /> <PackageReference Include="LinqKit.Microsoft.EntityFrameworkCore" Version="6.1.2" /> <PackageReference Include="NodaTime" Version="3.1.5" /> <PackageReference Include="Testcontainers.MsSql" Version="3.9.0" /> <ProjectReference Include="..\..\src\Microsoft.EntityFrameworkCore.DynamicLinq.EFCore6\Microsoft.EntityFrameworkCore.DynamicLinq.EFCore6.csproj" /> </ItemGroup> <ItemGroup> <Compile Include="..\System.Linq.Dynamic.Core.Tests\*.cs" /> <Compile Include="..\System.Linq.Dynamic.Core.Tests\*\*.cs" /> <Compile Include="..\System.Linq.Dynamic.Core.Tests\*\*\*.cs" /> </ItemGroup> <ItemGroup> <Compile Remove="TestResults\**" /> <EmbeddedResource Remove="TestResults\**" /> <None Remove="TestResults\**" /> </ItemGroup> </Project> ```
/content/code_sandbox/test/System.Linq.Dynamic.Core.Tests.Net6/System.Linq.Dynamic.Core.Tests.Net6.csproj
xml
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
760
```yaml - name: Home href: index.md - name: API Documentation href: obj/api/ ```
/content/code_sandbox/docfx/toc.yml
yaml
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
24
```powershell <# .SYNOPSIS Builds documentation for this project into static HTML output .NOTES Author: Stef Heyenrath - @sheyenrath .LINK path_to_url path_to_url #> # For running this script: "Set-ExecutionPolicy Bypass" param ( [Switch]$Serve = $false ) Write-Host "Starting docfx build process." -ForegroundColor Yellow $docfxArgs = @( "docfx.json" ) # Add '--serve' to arguments in order to start serving the site in place if ($Serve.IsPresent) { $docfxArgs = $docfxArgs + "--serve" } # Start the make process which uses Sphynx to convert RST to HTML Start-Process "docfx" -ArgumentList $docfxArgs -NoNewWindow -Wait ```
/content/code_sandbox/docfx/build-docs.ps1
powershell
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
182
```xml <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net5.0</TargetFramework> <LangVersion>10</LangVersion> <AssemblyName>System.Linq.Dynamic.Core.Tests</AssemblyName> <DebugType>full</DebugType> <SignAssembly>True</SignAssembly> <AssemblyOriginatorKeyFile>../../src/System.Linq.Dynamic.Core/System.Linq.Dynamic.Core.snk</AssemblyOriginatorKeyFile> <IsPackable>false</IsPackable> <DefineConstants>$(DefineConstants);NETCOREAPP;EFCORE;EFCORE_3X;NETCOREAPP3_1;AspNetCoreIdentity</DefineConstants> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" /> <PackageReference Include="xunit" Version="2.4.2" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.5"> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> <PackageReference Include="coverlet.collector" Version="6.0.2"> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> <PackageReference Include="Linq.PropertyTranslator.Core" Version="1.0.5" /> <PackageReference Include="QueryInterceptor.Core" Version="1.0.9" /> <PackageReference Include="NFluent" Version="2.8.0" /> <PackageReference Include="Moq" Version="4.18.2" /> <PackageReference Include="FluentAssertions" Version="6.8.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.0" /> <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="5.0.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.0" /> <PackageReference Include="LinqKit.Microsoft.EntityFrameworkCore" Version="5.1.2" /> <PackageReference Include="NodaTime" Version="3.1.5" /> <PackageReference Include="Testcontainers.MsSql" Version="3.9.0" /> <ProjectReference Include="..\..\src\Microsoft.EntityFrameworkCore.DynamicLinq.EFCore5\Microsoft.EntityFrameworkCore.DynamicLinq.EFCore5.csproj" /> </ItemGroup> <ItemGroup> <Compile Include="..\System.Linq.Dynamic.Core.Tests\*.cs" /> <Compile Include="..\System.Linq.Dynamic.Core.Tests\*\*.cs" /> <Compile Include="..\System.Linq.Dynamic.Core.Tests\*\*\*.cs" /> </ItemGroup> </Project> ```
/content/code_sandbox/test/System.Linq.Dynamic.Core.Tests.Net5/System.Linq.Dynamic.Core.Tests.Net5.csproj
xml
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
668
```xml <Project> <PropertyGroup> <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> <ApplicationIcon>../../resources/logo.ico</ApplicationIcon> <Authors>ZZZ Projects;Stef Heyenrath</Authors> <Company>ZZZ Projects</Company> <DefaultLanguage>en-us</DefaultLanguage> <GenerateDocumentationFile>true</GenerateDocumentationFile> <LangVersion>latest</LangVersion> <Nullable>enable</Nullable> <PackageIcon>logo.png</PackageIcon> <PackageReadmeFile>PackageReadme.md</PackageReadmeFile> <PackageProjectUrl>path_to_url <PackageReleaseNotes>Bugfixes and new Features. For details see CHANGELOG.md</PackageReleaseNotes> <PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign> <PublishRepositoryUrl>true</PublishRepositoryUrl> <RepositoryType>git</RepositoryType> <RepositoryUrl>path_to_url <SignAssembly>true</SignAssembly> </PropertyGroup> <ItemGroup> <None Include="../../resources/logo.png" Pack="true" PackagePath="" /> <None Include="../../PackageReadme.md" Pack="true" PackagePath=""/> </ItemGroup> </Project> ```
/content/code_sandbox/src/Directory.Build.props
xml
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
295
```smalltalk using System.Runtime.InteropServices; [assembly: ComVisible(false)] [assembly: Guid("D3804228-91F4-4502-9595-39584Ea20000")] ```
/content/code_sandbox/src/Z.EntityFramework.Classic.DynamicLinq/Properties/AssemblyInfo.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
37
```smalltalk namespace EntityFramework.DynamicLinq; /// <summary> /// A dummy class to determine if the assembly is using EntityFramework. /// </summary> public struct EFType { } ```
/content/code_sandbox/src/EntityFramework.DynamicLinq/EFType.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
37
```xml <Project Sdk="Microsoft.NET.Sdk" ToolsVersion="15.0"> <Import Project="../../version.xml" /> <PropertyGroup> <AssemblyName>Z.EntityFramework.Classic.DynamicLinq</AssemblyName> <AssemblyOriginatorKeyFile>Z.EntityFramework.Classic.DynamicLinq.snk</AssemblyOriginatorKeyFile> <AssemblyTitle>Z.EntityFramework.Classic.DynamicLinq</AssemblyTitle> <DefineConstants>EF</DefineConstants> <Description>Dynamic Linq extensions for Z.EntityFramework.Classic which adds Async support</Description> <PackageTags>system;linq;dynamic;Z.EntityFramework;core;async;classic</PackageTags> <ProjectGuid>{D3804228-91F4-4502-9595-39584Ea20000}</ProjectGuid> <TargetFrameworks>net45;netstandard2.0</TargetFrameworks> <Version>1.4.$(PatchVersion)</Version> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> <DebugType>full</DebugType> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)' == 'Release' "> <DebugType>portable</DebugType> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> </PropertyGroup> <ItemGroup> <Compile Include="..\System.Linq.Dynamic.Core\Res.cs" /> <Compile Include="..\System.Linq.Dynamic.Core\Compatibility\*.cs" /> <Compile Include="..\System.Linq.Dynamic.Core\Extensions\*.cs" /> <Compile Include="..\System.Linq.Dynamic.Core\Validation\*.cs" /> <Compile Include="..\Microsoft.EntityFrameworkCore.DynamicLinq\*.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\System.Linq.Dynamic.Core\System.Linq.Dynamic.Core.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="JetBrains.Annotations" Version="2022.3.1" PrivateAssets="All" /> <PackageReference Include="Z.EntityFramework.Classic" Version="7.1.7" /> </ItemGroup> </Project> ```
/content/code_sandbox/src/Z.EntityFramework.Classic.DynamicLinq/Z.EntityFramework.Classic.DynamicLinq.csproj
xml
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
455
```smalltalk using System.Runtime.InteropServices; [assembly: ComVisible(false)] [assembly: Guid("54415664-a73e-47af-b21f-e66b2db2ef14")] ```
/content/code_sandbox/src/EntityFramework.DynamicLinq/Properties/AssemblyInfo.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
36
```xml <Project Sdk="Microsoft.NET.Sdk" ToolsVersion="15.0"> <Import Project="../../version.xml" /> <PropertyGroup> <AssemblyName>EntityFramework.DynamicLinq</AssemblyName> <AssemblyOriginatorKeyFile>EntityFramework.DynamicLinq.snk</AssemblyOriginatorKeyFile> <AssemblyTitle>EntityFramework.DynamicLinq</AssemblyTitle> <DefineConstants>EF;EFDYNAMICFUNCTIONS</DefineConstants> <Description>Dynamic Linq extensions for EntityFramework which adds Async support</Description> <PackageTags>system;linq;dynamic;entityframework;core;async</PackageTags> <ProjectGuid>{D3804228-91F4-4502-9595-39584E510000}</ProjectGuid> <TargetFrameworks>net45;net452;net46;netstandard2.1</TargetFrameworks> <Version>1.4.$(PatchVersion)</Version> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> <DebugType>full</DebugType> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)' == 'Release' "> <DebugType>portable</DebugType> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> </PropertyGroup> <ItemGroup> <Compile Include="..\System.Linq.Dynamic.Core\Res.cs" /> <Compile Include="..\System.Linq.Dynamic.Core\Compatibility\*.cs" /> <Compile Include="..\System.Linq.Dynamic.Core\Extensions\*.cs" /> <Compile Include="..\System.Linq.Dynamic.Core\Validation\*.cs" /> <Compile Include="..\Microsoft.EntityFrameworkCore.DynamicLinq.EFCore3\*.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\System.Linq.Dynamic.Core\System.Linq.Dynamic.Core.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="JetBrains.Annotations" Version="2022.3.1" PrivateAssets="All" /> </ItemGroup> <ItemGroup> <PackageReference Include="EntityFramework" Version="6.5.0" /> </ItemGroup> </Project> ```
/content/code_sandbox/src/EntityFramework.DynamicLinq/EntityFramework.DynamicLinq.csproj
xml
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
471
```smalltalk using System.Runtime.InteropServices; [assembly: ComVisible(false)] #if !(NETSTANDARD2_1) [assembly: Guid("b467c675-c014-4b55-85b9-9578941d28c8")] #endif ```
/content/code_sandbox/src/Microsoft.EntityFrameworkCore.DynamicLinq.EFCore6/Properties/AssemblyInfo.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
49
```xml <Project Sdk="Microsoft.NET.Sdk" ToolsVersion="15.0"> <Import Project="../../version.xml" /> <PropertyGroup> <AssemblyName>Microsoft.EntityFrameworkCore.DynamicLinq</AssemblyName> <AssemblyOriginatorKeyFile>../Microsoft.EntityFrameworkCore.DynamicLinq.EFCore2/Microsoft.EntityFrameworkCore.DynamicLinq.snk</AssemblyOriginatorKeyFile> <AssemblyTitle>Microsoft.EntityFrameworkCore.DynamicLinq</AssemblyTitle> <DefineConstants>$(DefineConstants);EFCORE;EFCORE_3X;EFDYNAMICFUNCTIONS;ASYNCENUMERABLE</DefineConstants> <Description>Dynamic Linq extensions for Microsoft.EntityFrameworkCore which adds Async support</Description> <PackageTags>system;linq;dynamic;entityframework;core;async</PackageTags> <ProjectGuid>{D28F6393-B56B-40A2-AF67-E8D669F42546}</ProjectGuid> <TargetFrameworks>net6.0</TargetFrameworks> <Version>6.4.$(PatchVersion)</Version> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> <DebugType>full</DebugType> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)' == 'Release' "> <!--<IncludeSource>True</IncludeSource> <IncludeSymbols>True</IncludeSymbols> <PathMap>$(MSBuildProjectDirectory)=/</PathMap>--> <DebugType>portable</DebugType> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> </PropertyGroup> <PropertyGroup Condition=" '$(buildType)' == 'azure-pipelines-ci' "> <TargetFrameworks>net6.0</TargetFrameworks> </PropertyGroup> <ItemGroup> <Compile Include="..\System.Linq.Dynamic.Core\Res.cs" /> <Compile Include="..\System.Linq.Dynamic.Core\Compatibility\*.cs" /> <Compile Include="..\System.Linq.Dynamic.Core\Extensions\*.cs" /> <Compile Include="..\System.Linq.Dynamic.Core\Validation\*.cs" /> <Compile Include="..\Microsoft.EntityFrameworkCore.DynamicLinq.EFCore3\*.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\System.Linq.Dynamic.Core\System.Linq.Dynamic.Core.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="JetBrains.Annotations" Version="2022.3.1" PrivateAssets="All" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.0" /> </ItemGroup> </Project> ```
/content/code_sandbox/src/Microsoft.EntityFrameworkCore.DynamicLinq.EFCore6/Microsoft.EntityFrameworkCore.DynamicLinq.EFCore6.csproj
xml
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
556
```smalltalk using System.Runtime.InteropServices; [assembly: ComVisible(false)] #if !(NETSTANDARD2_1) [assembly: Guid("b467c675-c014-4b55-85b9-9578941d2ef7")] #endif ```
/content/code_sandbox/src/Microsoft.EntityFrameworkCore.DynamicLinq.EFCore8/Properties/AssemblyInfo.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
49
```xml <Project Sdk="Microsoft.NET.Sdk" ToolsVersion="15.0"> <Import Project="../../version.xml" /> <PropertyGroup> <AssemblyName>Microsoft.EntityFrameworkCore.DynamicLinq</AssemblyName> <AssemblyOriginatorKeyFile>../Microsoft.EntityFrameworkCore.DynamicLinq.EFCore2/Microsoft.EntityFrameworkCore.DynamicLinq.snk</AssemblyOriginatorKeyFile> <AssemblyTitle>Microsoft.EntityFrameworkCore.DynamicLinq</AssemblyTitle> <DefineConstants>$(DefineConstants);EFCORE;EFCORE_3X;EFDYNAMICFUNCTIONS;ASYNCENUMERABLE</DefineConstants> <Description>Dynamic Linq extensions for Microsoft.EntityFrameworkCore which adds Async support</Description> <PackageTags>system;linq;dynamic;entityframework;core;async</PackageTags> <ProjectGuid>{9000129D-322D-4FE6-9C47-75464577C374}</ProjectGuid> <TargetFrameworks>net8.0</TargetFrameworks> <Version>8.4.$(PatchVersion)</Version> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> <DebugType>full</DebugType> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)' == 'Release' "> <!--<IncludeSource>True</IncludeSource> <IncludeSymbols>True</IncludeSymbols> <PathMap>$(MSBuildProjectDirectory)=/</PathMap>--> <DebugType>portable</DebugType> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> </PropertyGroup> <PropertyGroup Condition=" '$(buildType)' == 'azure-pipelines-ci' "> <TargetFrameworks>net8.0</TargetFrameworks> </PropertyGroup> <ItemGroup> <Compile Include="..\System.Linq.Dynamic.Core\Res.cs" /> <Compile Include="..\System.Linq.Dynamic.Core\Compatibility\*.cs" /> <Compile Include="..\System.Linq.Dynamic.Core\Extensions\*.cs" /> <Compile Include="..\System.Linq.Dynamic.Core\Validation\*.cs" /> <Compile Include="..\Microsoft.EntityFrameworkCore.DynamicLinq.EFCore3\*.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\System.Linq.Dynamic.Core\System.Linq.Dynamic.Core.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="JetBrains.Annotations" Version="2022.3.1" PrivateAssets="All" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.0" /> </ItemGroup> </Project> ```
/content/code_sandbox/src/Microsoft.EntityFrameworkCore.DynamicLinq.EFCore8/Microsoft.EntityFrameworkCore.DynamicLinq.EFCore8.csproj
xml
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
555
```smalltalk using System.Runtime.InteropServices; [assembly: ComVisible(false)] #if !(NETSTANDARD2_1) [assembly: Guid("b467c675-c014-4b55-85b9-9578941d2ef7")] #endif ```
/content/code_sandbox/src/Microsoft.EntityFrameworkCore.DynamicLinq.EFCore7/Properties/AssemblyInfo.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
49
```xml <Project Sdk="Microsoft.NET.Sdk" ToolsVersion="15.0"> <Import Project="../../version.xml" /> <PropertyGroup> <AssemblyName>Microsoft.EntityFrameworkCore.DynamicLinq</AssemblyName> <AssemblyOriginatorKeyFile>../Microsoft.EntityFrameworkCore.DynamicLinq.EFCore2/Microsoft.EntityFrameworkCore.DynamicLinq.snk</AssemblyOriginatorKeyFile> <AssemblyTitle>Microsoft.EntityFrameworkCore.DynamicLinq</AssemblyTitle> <DefineConstants>$(DefineConstants);EFCORE;EFCORE_3X;EFDYNAMICFUNCTIONS;ASYNCENUMERABLE</DefineConstants> <Description>Dynamic Linq extensions for Microsoft.EntityFrameworkCore which adds Async support</Description> <PackageTags>system;linq;dynamic;entityframework;core;async</PackageTags> <ProjectGuid>{FB2F4C99-EC34-4D29-87E2-944B25D90ef7}</ProjectGuid> <TargetFrameworks>net6.0;net7.0</TargetFrameworks> <Version>7.4.$(PatchVersion)</Version> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> <DebugType>full</DebugType> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)' == 'Release' "> <!--<IncludeSource>True</IncludeSource> <IncludeSymbols>True</IncludeSymbols> <PathMap>$(MSBuildProjectDirectory)=/</PathMap>--> <DebugType>portable</DebugType> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> </PropertyGroup> <PropertyGroup Condition=" '$(buildType)' == 'azure-pipelines-ci' "> <TargetFrameworks>net6.0;net7.0</TargetFrameworks> </PropertyGroup> <ItemGroup> <Compile Include="..\System.Linq.Dynamic.Core\Res.cs" /> <Compile Include="..\System.Linq.Dynamic.Core\Compatibility\*.cs" /> <Compile Include="..\System.Linq.Dynamic.Core\Extensions\*.cs" /> <Compile Include="..\System.Linq.Dynamic.Core\Validation\*.cs" /> <Compile Include="..\Microsoft.EntityFrameworkCore.DynamicLinq.EFCore3\*.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\System.Linq.Dynamic.Core\System.Linq.Dynamic.Core.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="JetBrains.Annotations" Version="2022.3.1" PrivateAssets="All" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.0" /> </ItemGroup> </Project> ```
/content/code_sandbox/src/Microsoft.EntityFrameworkCore.DynamicLinq.EFCore7/Microsoft.EntityFrameworkCore.DynamicLinq.EFCore7.csproj
xml
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
569
```smalltalk using System.Runtime.InteropServices; [assembly: ComVisible(false)] #if !(NETSTANDARD2_0) [assembly: Guid("b467c675-c014-4be3-85b9-9578941d28c8")] #endif ```
/content/code_sandbox/src/Microsoft.EntityFrameworkCore.DynamicLinq.EFCore2/Properties/AssemblyInfo.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
49
```xml <Project Sdk="Microsoft.NET.Sdk" ToolsVersion="15.0"> <Import Project="../../version.xml" /> <PropertyGroup> <AssemblyName>Microsoft.EntityFrameworkCore.DynamicLinq</AssemblyName> <AssemblyOriginatorKeyFile>Microsoft.EntityFrameworkCore.DynamicLinq.snk</AssemblyOriginatorKeyFile> <AssemblyTitle>Microsoft.EntityFrameworkCore.DynamicLinq</AssemblyTitle> <DefineConstants>$(DefineConstants);EFCORE;EFCORE_2X;EFDYNAMICFUNCTIONS</DefineConstants> <Description>Dynamic Linq extensions for Microsoft.EntityFrameworkCore which adds Async support</Description> <PackageTags>system;linq;dynamic;entityframework;core;async</PackageTags> <ProjectGuid>{D3804228-91F4-4502-9595-39584E510001}</ProjectGuid> <TargetFrameworks>netstandard2.0</TargetFrameworks> <Version>2.4.$(PatchVersion)</Version> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> <DebugType>full</DebugType> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)' == 'Release' "> <DebugType>portable</DebugType> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> </PropertyGroup> <PropertyGroup Condition=" '$(buildType)' == 'azure-pipelines-ci' "> <TargetFrameworks>netstandard2.0</TargetFrameworks> </PropertyGroup> <ItemGroup> <Compile Include="..\System.Linq.Dynamic.Core\Res.cs" /> <Compile Include="..\System.Linq.Dynamic.Core\Compatibility\*.cs" /> <Compile Include="..\System.Linq.Dynamic.Core\Extensions\*.cs" /> <Compile Include="..\System.Linq.Dynamic.Core\Validation\*.cs" /> <Compile Include="..\Microsoft.EntityFrameworkCore.DynamicLinq.EFCore3\*.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\System.Linq.Dynamic.Core\System.Linq.Dynamic.Core.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="JetBrains.Annotations" Version="2022.3.1" PrivateAssets="All" /> <PackageReference Include="System.Reflection.Emit" Version="4.3.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.1" /> </ItemGroup> </Project> ```
/content/code_sandbox/src/Microsoft.EntityFrameworkCore.DynamicLinq.EFCore2/Microsoft.EntityFrameworkCore.DynamicLinq.EFCore2.csproj
xml
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
522
```smalltalk using System.IO; using System.Reflection; using System.Collections.Generic; using System.Linq.Dynamic.Core.Validation; namespace System.Linq.Dynamic.Core; internal class DefaultAssemblyHelper(ParsingConfig parsingConfig) : IAssemblyHelper { private readonly ParsingConfig _config = Check.NotNull(parsingConfig); public Assembly[] GetAssemblies() { #if UAP10_0 || NETSTANDARD || WPSL throw new NotSupportedException(); #elif NET35 return AppDomain.CurrentDomain.GetAssemblies(); #else // path_to_url var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList(); var loadedPaths = new List<string>(); foreach (var loadedAssembly in loadedAssemblies) { try { if (!loadedAssembly.IsDynamic) { loadedPaths.Add(loadedAssembly.Location); } } catch { // Ignore } } if (!_config.LoadAdditionalAssembliesFromCurrentDomainBaseDirectory) { return loadedAssemblies.ToArray(); } string[] referencedPaths; try { referencedPaths = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll"); } catch { referencedPaths = []; } var pathsToLoad = referencedPaths .Where(referencedPath => !loadedPaths.Contains(referencedPath, StringComparer.InvariantCultureIgnoreCase)) .ToArray(); foreach (var path in pathsToLoad) { try { loadedAssemblies.Add(AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(path))); } catch { // Ignore } } return loadedAssemblies.ToArray(); #endif } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/DefaultAssemblyHelper.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
352
```smalltalk using System.Reflection; namespace System.Linq.Dynamic.Core; /// <summary> /// IAssemblyHelper interface which is used to retrieve assemblies that have been loaded into the execution context of this application domain. /// </summary> public interface IAssemblyHelper { /// <summary> /// Gets the assemblies that have been loaded into the execution context of this application domain. /// </summary> /// /// <returns> /// An array of assemblies in this application domain. /// </returns> Assembly[] GetAssemblies(); } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/IAssemblyHelper.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
110
```smalltalk #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member using System.Collections; using System.Text.RegularExpressions; using JetBrains.Annotations; namespace System.Linq.Dynamic.Core { #if NET46_OR_GREATER || NET5_0_OR_GREATER || NETCOREAPP2_1_OR_GREATER || NETSTANDARD1_3_OR_GREATER || UAP10_0 /// <summary> /// Provides a set of static extension methods for querying data structures that implement <see cref="IQueryable"/>. /// It supports a FormattableString string as predicate. /// <seealso cref="DynamicQueryableExtensions"/> /// </summary> public static class DynamicQueryableWithFormattableStringExtensions { private static readonly Regex ReplaceArgumentsRegex = new(@"{(\d+)}", RegexOptions.Compiled); public static IQueryable WhereInterpolated([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.Where(source, config, predicateStr, args); } public static IQueryable WhereInterpolated([NotNull] this IQueryable source, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.Where(source, predicateStr, args); } public static IQueryable<TSource> WhereInterpolated<TSource>([NotNull] this IQueryable<TSource> source, [NotNull] ParsingConfig config, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.Where(source, config, predicateStr, args); } public static IQueryable<TSource> WhereInterpolated<TSource>([NotNull] this IQueryable<TSource> source, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.Where(source, predicateStr, args); } [PublicAPI] public static bool AllInterpolated([NotNull] this IQueryable source, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.All(source, predicateStr, args); } [PublicAPI] public static bool AllInterpolated([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.All(source, config, predicateStr, args); } [PublicAPI] public static bool AnyInterpolated([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.Any(source, config, predicateStr, args); } public static bool AnyInterpolated([NotNull] this IQueryable source, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.Any(source, predicateStr, args); } [PublicAPI] public static double AverageInterpolated([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.Average(source, config, predicateStr, args); } [PublicAPI] public static double AverageInterpolated([NotNull] this IQueryable source, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.Average(source, predicateStr, args); } public static dynamic SingleInterpolated([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.Single(source, config, predicateStr, args); } public static dynamic SingleInterpolated([NotNull] this IQueryable source, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.Single(source, predicateStr, args); } public static dynamic SingleOrDefaultInterpolated([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.SingleOrDefault(source, config, predicateStr, args); } public static dynamic SingleOrDefaultInterpolated([NotNull] this IQueryable source, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.SingleOrDefault(source, predicateStr, args); } public static IQueryable SkipWhileInterpolated([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.SkipWhile(source, config, predicateStr, args); } public static IQueryable SkipWhileInterpolated([NotNull] this IQueryable source, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.SkipWhile(source, predicateStr, args); } public static IQueryable TakeWhileInterpolated([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.TakeWhile(source, config, predicateStr, args); } public static IQueryable TakeWhileInterpolated([NotNull] this IQueryable source, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.TakeWhile(source, predicateStr, args); } [PublicAPI] public static object SumInterpolated([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.Sum(source, config, predicateStr, args); } [PublicAPI] public static object SumInterpolated([NotNull] this IQueryable source, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.Sum(source, predicateStr, args); } [PublicAPI] public static int CountInterpolated([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.Count(source, config, predicateStr, args); } public static int CountInterpolated([NotNull] this IQueryable source, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.Count(source, predicateStr, args); } public static dynamic FirstInterpolated([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.First(source, config, predicateStr, args); } public static dynamic FirstInterpolated([NotNull] this IQueryable source, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.First(source, predicateStr, args); } public static dynamic FirstOrDefaultInterpolated([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.FirstOrDefault(source, config, predicateStr, args); } public static dynamic FirstOrDefaultInterpolated([NotNull] this IQueryable source, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.FirstOrDefault(source, predicateStr, args); } public static dynamic LastInterpolated([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.Last(source, config, predicateStr, args); } public static dynamic LastInterpolated([NotNull] this IQueryable source, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.Last(source, predicateStr, args); } public static dynamic LastOrDefaultInterpolated([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.LastOrDefault(source, config, predicateStr, args); } public static dynamic LastOrDefaultInterpolated([NotNull] this IQueryable source, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.LastOrDefault(source, predicateStr, args); } [PublicAPI] public static long LongCountInterpolated([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.LongCount(source, config, predicateStr, args); } public static long LongCountInterpolated([NotNull] this IQueryable source, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.LongCount(source, predicateStr, args); } [PublicAPI] public static object MaxInterpolated([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.Max(source, config, predicateStr, args); } [PublicAPI] public static object MaxInterpolated([NotNull] this IQueryable source, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.Max(source, predicateStr, args); } [PublicAPI] public static object MinInterpolated([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.Min(source, config, predicateStr, args); } [PublicAPI] public static object MinInterpolated([NotNull] this IQueryable source, [NotNull] FormattableString predicate) { var predicateStr = ParseFormattableString(predicate, out var args); return DynamicQueryableExtensions.Min(source, predicateStr, args); } public static IQueryable SelectInterpolated([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString selector) { var selectorStr = ParseFormattableString(selector, out var args); return DynamicQueryableExtensions.Select(source, config, selectorStr, args); } public static IQueryable SelectInterpolated([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] Type resultType, [NotNull] FormattableString selector) { var selectorStr = ParseFormattableString(selector, out var args); return DynamicQueryableExtensions.Select(source, config, resultType, selectorStr, args); } public static IQueryable SelectInterpolated([NotNull] this IQueryable source, [NotNull] FormattableString selector) { var selectorStr = ParseFormattableString(selector, out var args); return DynamicQueryableExtensions.Select(source, selectorStr, args); } public static IQueryable<TResult> SelectInterpolated<TResult>([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString selector) { var selectorStr = ParseFormattableString(selector, out var args); return DynamicQueryableExtensions.Select<TResult>(source, config, selectorStr, args); } public static IQueryable<TResult> SelectInterpolated<TResult>([NotNull] this IQueryable source, [NotNull] FormattableString selector) { var selectorStr = ParseFormattableString(selector, out var args); return DynamicQueryableExtensions.Select<TResult>(source, selectorStr, args); } public static IQueryable SelectManyInterpolated([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString collectionSelector, [NotNull] FormattableString resultSelector) { var collectionSelectorStr = ParseFormattableString(collectionSelector, out var collectionSelectorArgs); var resultSelectorStr = ParseFormattableString(resultSelector, out var resultSelectorArgs); return DynamicQueryableExtensions.SelectMany(source, config, collectionSelectorStr, resultSelectorStr, collectionSelectorArgs, resultSelectorArgs); } public static IQueryable SelectManyInterpolated([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString selector) { var selectorStr = ParseFormattableString(selector, out var args); return DynamicQueryableExtensions.SelectMany(source, config, selectorStr, args); } public static IQueryable SelectManyInterpolated([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] Type resultType, [NotNull] FormattableString selector) { var selectorStr = ParseFormattableString(selector, out var args); return DynamicQueryableExtensions.SelectMany(source, config, resultType, selectorStr, args); } public static IQueryable SelectManyInterpolated([NotNull] this IQueryable source, [NotNull] FormattableString collectionSelector, [NotNull] FormattableString resultSelector) { var collectionSelectorStr = ParseFormattableString(collectionSelector, out var collectionSelectorArgs); var resultSelectorStr = ParseFormattableString(resultSelector, out var resultSelectorArgs); return DynamicQueryableExtensions.SelectMany(source, collectionSelectorStr, collectionSelectorArgs, resultSelectorStr, resultSelectorArgs); } public static IQueryable SelectManyInterpolated([NotNull] this IQueryable source, [NotNull] FormattableString selector) { var selectorStr = ParseFormattableString(selector, out var args); return DynamicQueryableExtensions.SelectMany(source, selectorStr, args); } public static IQueryable SelectManyInterpolated([NotNull] this IQueryable source, [NotNull] Type resultType, [NotNull] FormattableString selector) { var selectorStr = ParseFormattableString(selector, out var args); return DynamicQueryableExtensions.SelectMany(source, resultType, selectorStr, args); } public static IQueryable<TResult> SelectManyInterpolated<TResult>([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString selector) { var selectorStr = ParseFormattableString(selector, out var args); return DynamicQueryableExtensions.SelectMany<TResult>(source, config, selectorStr, args); } public static IQueryable<TResult> SelectManyInterpolated<TResult>([NotNull] this IQueryable source, [NotNull] FormattableString selector) { var selectorStr = ParseFormattableString(selector, out var args); return DynamicQueryableExtensions.SelectMany<TResult>(source, selectorStr, args); } public static IOrderedQueryable OrderByInterpolated([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString ordering, IComparer comparer) { var orderingStr = ParseFormattableString(ordering, out var args); return DynamicQueryableExtensions.OrderBy(source, config, orderingStr, comparer, args); } public static IOrderedQueryable OrderByInterpolated([NotNull] this IQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString ordering) { var orderingStr = ParseFormattableString(ordering, out var args); return DynamicQueryableExtensions.OrderBy(source, config, orderingStr, args); } public static IOrderedQueryable OrderByInterpolated([NotNull] this IQueryable source, [NotNull] FormattableString ordering, IComparer comparer) { var orderingStr = ParseFormattableString(ordering, out var args); return DynamicQueryableExtensions.OrderBy(source, orderingStr, comparer, args); } public static IOrderedQueryable OrderByInterpolated([NotNull] this IQueryable source, [NotNull] FormattableString ordering) { var orderingStr = ParseFormattableString(ordering, out var args); return DynamicQueryableExtensions.OrderBy(source, orderingStr, args); } public static IOrderedQueryable<TSource> OrderByInterpolated<TSource>([NotNull] this IQueryable<TSource> source, [NotNull] ParsingConfig config, [NotNull] FormattableString ordering, IComparer comparer) { var orderingStr = ParseFormattableString(ordering, out var args); return DynamicQueryableExtensions.OrderBy(source, config, orderingStr, comparer, args); } public static IOrderedQueryable<TSource> OrderByInterpolated<TSource>([NotNull] this IQueryable<TSource> source, [NotNull] ParsingConfig config, [NotNull] FormattableString ordering) { var orderingStr = ParseFormattableString(ordering, out var args); return DynamicQueryableExtensions.OrderBy(source, config, orderingStr, args); } public static IOrderedQueryable<TSource> OrderByInterpolated<TSource>([NotNull] this IQueryable<TSource> source, [NotNull] FormattableString ordering, IComparer comparer) { var orderingStr = ParseFormattableString(ordering, out var args); return DynamicQueryableExtensions.OrderBy(source, orderingStr, comparer, args); } public static IOrderedQueryable<TSource> OrderByInterpolated<TSource>([NotNull] this IQueryable<TSource> source, [NotNull] FormattableString ordering) { var orderingStr = ParseFormattableString(ordering, out var args); return DynamicQueryableExtensions.OrderBy(source, orderingStr, args); } public static IOrderedQueryable ThenByInterpolated([NotNull] this IOrderedQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString ordering, IComparer comparer) { var orderingStr = ParseFormattableString(ordering, out var args); return DynamicQueryableExtensions.ThenBy(source, config, orderingStr, comparer, args); } public static IOrderedQueryable ThenByInterpolated([NotNull] this IOrderedQueryable source, [NotNull] ParsingConfig config, [NotNull] FormattableString ordering) { var orderingStr = ParseFormattableString(ordering, out var args); return DynamicQueryableExtensions.ThenBy(source, config, orderingStr, args); } public static IOrderedQueryable ThenByInterpolated([NotNull] this IOrderedQueryable source, [NotNull] FormattableString ordering, IComparer comparer) { var orderingStr = ParseFormattableString(ordering, out var args); return DynamicQueryableExtensions.ThenBy(source, orderingStr, comparer, args); } public static IOrderedQueryable ThenByInterpolated([NotNull] this IOrderedQueryable source, [NotNull] FormattableString ordering) { var orderingStr = ParseFormattableString(ordering, out var args); return DynamicQueryableExtensions.ThenBy(source, orderingStr, args); } public static IOrderedQueryable<TSource> ThenByInterpolated<TSource>([NotNull] this IOrderedQueryable<TSource> source, [NotNull] ParsingConfig config, [NotNull] FormattableString ordering, IComparer comparer) { var orderingStr = ParseFormattableString(ordering, out var args); return DynamicQueryableExtensions.ThenBy(source, config, orderingStr, comparer, args); } public static IOrderedQueryable<TSource> ThenByInterpolated<TSource>([NotNull] this IOrderedQueryable<TSource> source, [NotNull] ParsingConfig config, [NotNull] FormattableString ordering) { var orderingStr = ParseFormattableString(ordering, out var args); return DynamicQueryableExtensions.ThenBy(source, config, orderingStr, args); } public static IOrderedQueryable<TSource> ThenByInterpolated<TSource>([NotNull] this IOrderedQueryable<TSource> source, [NotNull] FormattableString ordering, IComparer comparer) { var orderingStr = ParseFormattableString(ordering, out var args); return DynamicQueryableExtensions.ThenBy(source, orderingStr, comparer, args); } public static IOrderedQueryable<TSource> ThenByInterpolated<TSource>([NotNull] this IOrderedQueryable<TSource> source, [NotNull] FormattableString ordering) { var orderingStr = ParseFormattableString(ordering, out var args); return DynamicQueryableExtensions.ThenBy(source, orderingStr, args); } private static string ParseFormattableString(FormattableString predicate, out object[] args) { args = predicate.GetArguments(); return ReplaceArgumentsRegex.Replace(predicate.Format, "@$1"); // replace {0} with @0 } } #endif } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/DynamicQueryableWithFormattableStringExtensions.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
4,692
```smalltalk using System.Linq.Expressions; namespace System.Linq.Dynamic.Core { internal class DynamicOrdering { public Expression Selector; public bool Ascending; public string MethodName; } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/DynamicOrdering.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
42
```xml <Project Sdk="Microsoft.NET.Sdk" ToolsVersion="15.0"> <Import Project="../../version.xml" /> <PropertyGroup> <AssemblyName>System.Linq.Dynamic.Core</AssemblyName> <AssemblyOriginatorKeyFile>System.Linq.Dynamic.Core.snk</AssemblyOriginatorKeyFile> <AssemblyTitle>System.Linq.Dynamic.Core</AssemblyTitle> <Authors>ZZZ Projects;Stef Heyenrath;Microsoft;Scott Guthrie;King Wilder;Nathan Arnott</Authors> <Description>This is a .NETStandard / .NET Core port of the the Microsoft assembly for the .Net 4.0 Dynamic language functionality.</Description> <PackageTags>system;linq;dynamic;core;dotnet;NETCoreApp;NETStandard</PackageTags> <ProjectGuid>{D3804228-91F4-4502-9595-39584E510002}</ProjectGuid> <TargetFrameworks>net35;net40;net45;net452;net46;netstandard1.3;netstandard2.0;netstandard2.1;uap10.0;netcoreapp2.1;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0</TargetFrameworks> <Version>1.4.$(PatchVersion)</Version> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> <DebugType>full</DebugType> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)' == 'Release' "> <!--<IncludeSource>True</IncludeSource> <IncludeSymbols>True</IncludeSymbols> <PathMap>$(MSBuildProjectDirectory)=/</PathMap>--> <DebugType>portable</DebugType> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> </PropertyGroup> <PropertyGroup Condition=" '$(buildType)' == 'azure-pipelines-ci' "> <TargetFrameworks>net40;net45;net46;netstandard1.3;netstandard2.0;netcoreapp2.1;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0</TargetFrameworks> </PropertyGroup> <PropertyGroup Condition=" '$(TargetFramework)' == 'netstandard1.3' "> <DefineConstants>$(DefineConstants);NETSTANDARD</DefineConstants> </PropertyGroup> <PropertyGroup Condition=" '$(TargetFramework)' == 'netcoreapp3.1' or '$(TargetFramework)' == 'net5.0' or '$(TargetFramework)' == 'net6.0' or '$(TargetFramework)' == 'net7.0' or '$(TargetFramework)' == 'net8.0' "> <DefineConstants>$(DefineConstants);ASYNCENUMERABLE</DefineConstants> </PropertyGroup> <PropertyGroup Condition="'$(TargetFramework)' == 'uap10.0'"> <CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies> <NugetTargetMoniker>UAP,Version=v10.0</NugetTargetMoniker> <TargetPlatformIdentifier>UAP</TargetPlatformIdentifier> <TargetPlatformVersion>10.0.19041.0</TargetPlatformVersion> <TargetPlatformMinVersion>10.0.10240.0</TargetPlatformMinVersion> <TargetFrameworkIdentifier>.NETCore</TargetFrameworkIdentifier> <TargetFrameworkVersion>v5.0</TargetFrameworkVersion> <DefineConstants>$(DefineConstants);WINDOWS_UWP;UAP10_0</DefineConstants> <LanguageTargets>$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets</LanguageTargets> </PropertyGroup> <ItemGroup> <None Remove="LinkerConfig.xml" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="LinkerConfig.xml"> <LogicalName>$(MSBuildProjectName).xml</LogicalName> </EmbeddedResource> </ItemGroup> <ItemGroup> <PackageReference Include="JetBrains.Annotations" Version="2022.3.1" PrivateAssets="All" /> </ItemGroup> <ItemGroup Condition=" '$(TargetFramework)' == 'net35' "> <PackageReference Include="NetLegacySupport.ConcurrentDictionary"> <Version>1.1.1</Version> </PackageReference> </ItemGroup> <ItemGroup Condition=" '$(TargetFramework)' == 'netstandard1.3' "> <PackageReference Include="System.ComponentModel.TypeConverter" Version="4.3.0" /> <PackageReference Include="System.Dynamic.Runtime" Version="4.3.0" /> <PackageReference Include="System.Reflection.Emit" Version="4.3.0" /> <PackageReference Include="System.Linq.Queryable" Version="4.3.0" /> <PackageReference Include="System.Reflection.TypeExtensions" Version="4.3.0" /> <PackageReference Include="System.Diagnostics.TraceSource" Version="4.3.0" /> </ItemGroup> <ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' "> <PackageReference Include="System.Reflection.Emit" Version="4.3.0" /> </ItemGroup> <ItemGroup Condition=" '$(TargetFramework)' == 'uap10.0' "> <PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform" Version="6.0.10" /> <PackageReference Include="System.Diagnostics.TraceSource" Version="4.0.0" /> <PackageReference Include="System.ComponentModel.TypeConverter" Version="4.1.0" /> </ItemGroup> </Project> ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/System.Linq.Dynamic.Core.csproj
xml
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
1,258
```smalltalk namespace System.Linq.Dynamic.Core; /// <summary> /// Interface for QueryableAnalyzer. /// </summary> public interface IQueryableAnalyzer { /// <summary> /// Determines whether the specified query (and provider) supports LinqToObjects. /// </summary> /// <param name="query">The query to check.</param> /// <param name="provider">The provider to check (can be null).</param> /// <returns>true/false</returns> bool SupportsLinqToObjects(IQueryable query, IQueryProvider? provider = null); } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/IQueryableAnalyzer.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
118
```xml <?xml version="1.0" encoding="utf-8" ?> <!-- IL linker format: path_to_url#link-xml-file-examples --> <linker> <!--Use to solve some mono problems see path_to_url and path_to_url --> <assembly fullname="System.Core"> <type fullname="System.Linq.Queryable" preserve="all" /> </assembly> <assembly fullname="System.Linq.Dynamic.Core"> <type fullname="System.Linq.Dynamic.Core.DynamicEnumerableExtensions" preserve="all" /> </assembly> </linker> ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/LinkerConfig.xml
xml
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
117
```smalltalk using System.Collections; using System.Collections.Generic; using System.Linq.Dynamic.Core.Validation; using System.Reflection; namespace System.Linq.Dynamic.Core { /// <summary> /// Define extensions on <see cref="IEnumerable"/>. /// </summary> public static class DynamicEnumerableExtensions { private static readonly MethodInfo ToDynamicArrayGenericMethod; static DynamicEnumerableExtensions() { ToDynamicArrayGenericMethod = typeof(DynamicEnumerableExtensions).GetTypeInfo().GetDeclaredMethods("ToDynamicArray") .First(x => x.IsGenericMethod); } /// <summary> /// Creates an array of dynamic objects from a <see cref="IEnumerable"/>. /// </summary> /// <param name="source">A <see cref="IEnumerable"/> to create an array from.</param> /// <returns>An array that contains the elements from the input sequence.</returns> #if NET35 public static object[] ToDynamicArray(this IEnumerable source) { return CastToArray<object>(Check.NotNull(source)); } #else public static dynamic[] ToDynamicArray(this IEnumerable source) { return CastToArray<dynamic>(Check.NotNull(source)); } #endif /// <summary> /// Creates an array of dynamic objects from a <see cref="IEnumerable"/>. /// </summary> /// <typeparam name="T">The generic type.</typeparam> /// <param name="source">A <see cref="IEnumerable"/> to create an array from.</param> /// <returns>An Array{T} that contains the elements from the input sequence.</returns> public static T[] ToDynamicArray<T>(this IEnumerable source) { return CastToArray<T>(Check.NotNull(source)); } /// <summary> /// Creates an array of dynamic objects from a <see cref="IEnumerable"/>. /// </summary> /// <param name="source">A <see cref="IEnumerable"/> to create an array from.</param> /// <param name="type">A <see cref="Type"/> cast to.</param> /// <returns>An Array that contains the elements from the input sequence.</returns> #if NET35 public static object[] ToDynamicArray(this IEnumerable source, Type type) #else public static dynamic[] ToDynamicArray(this IEnumerable source, Type type) #endif { Check.NotNull(source); Check.NotNull(type); IEnumerable result = (IEnumerable)ToDynamicArrayGenericMethod.MakeGenericMethod(type).Invoke(source, new object[] { source }); #if NET35 return CastToArray<object>(result); #else return CastToArray<dynamic>(result); #endif } /// <summary> /// Creates a list of dynamic objects from a <see cref="IEnumerable"/>. /// </summary> /// <param name="source">A <see cref="IEnumerable"/> to create an array from.</param> /// <returns>A List that contains the elements from the input sequence.</returns> #if NET35 public static List<object> ToDynamicList(this IEnumerable source) #else public static List<dynamic> ToDynamicList(this IEnumerable source) #endif { #if NET35 return CastToList<object>(Check.NotNull(source)); #else return CastToList<dynamic>(Check.NotNull(source)); #endif } /// <summary> /// Creates a list of dynamic objects from a <see cref="IEnumerable"/>. /// </summary> /// <param name="source">A <see cref="IEnumerable"/> to create an array from.</param> /// <param name="type">A <see cref="Type"/> cast to.</param> /// <returns>A List that contains the elements from the input sequence.</returns> #if NET35 public static List<object> ToDynamicList(this IEnumerable source, Type type) #else public static List<dynamic> ToDynamicList(this IEnumerable source, Type type) #endif { return ToDynamicArray(Check.NotNull(source), Check.NotNull(type)).ToList(); } /// <summary> /// Creates a list of dynamic objects from a <see cref="IEnumerable"/>. /// </summary> /// <typeparam name="T">Generic Type</typeparam> /// <param name="source">A <see cref="IEnumerable"/> to create an array from.</param> /// <returns>A List{T} that contains the elements from the input sequence.</returns> public static List<T> ToDynamicList<T>(this IEnumerable source) { return CastToList<T>(Check.NotNull(source)); } internal static T[] CastToArray<T>(IEnumerable source) { return source.Cast<T>().ToArray(); } internal static List<T> CastToList<T>(IEnumerable source) { return source.Cast<T>().ToList(); } } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/DynamicEnumerableExtensions.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
978
```smalltalk using System.Linq.Expressions; namespace System.Linq.Dynamic.Core; internal static class ParameterExpressionHelper { public static ParameterExpression CreateParameterExpression(Type type, string name, bool renameEmpty = false) { string paramName = name; if (renameEmpty && paramName.IsNullOrWhiteSpace()) { paramName = GenerateRandomWord(); } return Expression.Parameter(type, paramName); } /// <summary> /// Generates a random 16 character word derived from a Guid value. /// </summary> internal static string GenerateRandomWord() { const int wordLength = 16; const int diff = 'A' - '0'; return string.Concat(Guid.NewGuid().ToString(@"N").Select(c => (char)(c + diff)).Take(wordLength)).ToLower(); } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/ParameterExpressionHelper.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
164
```smalltalk #if !(UAP10_0) using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq.Dynamic.Core.Validation; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Text; using System.Threading; namespace System.Linq.Dynamic.Core; /// <summary> /// A factory to create dynamic classes, based on <see href="path_to_url" />. /// </summary> public static class DynamicClassFactory { private const string DynamicAssemblyName = "System.Linq.Dynamic.Core.DynamicClasses, Version=1.0.0.0"; private const string DynamicModuleName = "System.Linq.Dynamic.Core.DynamicClasses"; // Some objects we cache private static readonly CustomAttributeBuilder CompilerGeneratedAttributeBuilder = new(typeof(CompilerGeneratedAttribute).GetConstructor(Type.EmptyTypes)!, []); private static readonly CustomAttributeBuilder DebuggerBrowsableAttributeBuilder = new(typeof(DebuggerBrowsableAttribute).GetConstructor([typeof(DebuggerBrowsableState)])!, [DebuggerBrowsableState.Never]); private static readonly CustomAttributeBuilder DebuggerHiddenAttributeBuilder = new(typeof(DebuggerHiddenAttribute).GetConstructor(Type.EmptyTypes)!, []); private static readonly ConstructorInfo ObjectCtor = typeof(object).GetConstructor(Type.EmptyTypes)!; #if UAP10_0 || NETSTANDARD private static readonly MethodInfo ObjectToString = typeof(object).GetMethod(nameof(ToString), BindingFlags.Instance | BindingFlags.Public)!; #else private static readonly MethodInfo ObjectToString = typeof(object).GetMethod(nameof(ToString), BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null)!; #endif private static readonly ConstructorInfo StringBuilderCtor = typeof(StringBuilder).GetConstructor(Type.EmptyTypes)!; #if UAP10_0 || NETSTANDARD private static readonly MethodInfo StringBuilderAppendString = typeof(StringBuilder).GetMethod(nameof(StringBuilder.Append), [typeof(string)])!; private static readonly MethodInfo StringBuilderAppendObject = typeof(StringBuilder).GetMethod(nameof(StringBuilder.Append), [typeof(object)])!; #else private static readonly MethodInfo StringBuilderAppendString = typeof(StringBuilder).GetMethod(nameof(StringBuilder.Append), BindingFlags.Instance | BindingFlags.Public, null, [typeof(string)], null)!; private static readonly MethodInfo StringBuilderAppendObject = typeof(StringBuilder).GetMethod(nameof(StringBuilder.Append), BindingFlags.Instance | BindingFlags.Public, null, [typeof(object)], null)!; #endif private static readonly Type EqualityComparer = typeof(EqualityComparer<>); private static readonly ConcurrentDictionary<string, Type> GeneratedTypes = new(); private static readonly ModuleBuilder ModuleBuilder; private static int _index = -1; /// <summary> /// Initializes the <see cref="DynamicClassFactory"/> class. /// </summary> static DynamicClassFactory() { var assemblyName = new AssemblyName(DynamicAssemblyName); var assemblyBuilder = AssemblyBuilderFactory.DefineDynamicAssembly ( assemblyName, #if NET35 AssemblyBuilderAccess.Run #else AssemblyBuilderAccess.RunAndCollect #endif ); ModuleBuilder = assemblyBuilder.DefineDynamicModule(DynamicModuleName); } /// <summary> /// Create a GenericComparerType based on the GenericType and an instance of a <see cref="IComparer"/>. /// </summary> /// <param name="comparerGenericType">The GenericType</param> /// <param name="comparerType">The <see cref="IComparer"/> instance</param> /// <returns>Type</returns> public static Type CreateGenericComparerType(Type comparerGenericType, Type comparerType) { Check.NotNull(comparerGenericType); Check.NotNull(comparerType); var key = $"{comparerGenericType.FullName}_{comparerType.FullName}"; // ReSharper disable once InconsistentlySynchronizedField if (!GeneratedTypes.TryGetValue(key, out var type)) { // We create only a single class at a time, through this lock // Note that this is a variant of the double-checked locking. // It is safe because we are using a thread safe class. lock (GeneratedTypes) { if (!GeneratedTypes.TryGetValue(key, out type)) { var compareMethodGeneric = comparerGenericType.GetMethod("Compare")!; var compareMethod = typeof(IComparer).GetMethod("Compare")!; var compareCtor = comparerType.GetConstructor(Type.EmptyTypes)!; var genericType = comparerGenericType.GetGenericArguments()[0]; var typeBuilder = ModuleBuilder.DefineType(key, TypeAttributes.AnsiClass | TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoLayout, typeof(object)); typeBuilder.AddInterfaceImplementation(comparerGenericType); var fieldBuilder = typeBuilder.DefineField("_c", typeof(IComparer), FieldAttributes.Private | FieldAttributes.InitOnly); var constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig, CallingConventions.HasThis, Type.EmptyTypes); var constructorIL = constructorBuilder.GetILGenerator(); constructorIL.Emit(OpCodes.Ldarg_0); constructorIL.Emit(OpCodes.Call, ObjectCtor); constructorIL.Emit(OpCodes.Ldarg_0); constructorIL.Emit(OpCodes.Newobj, compareCtor); constructorIL.Emit(OpCodes.Stfld, fieldBuilder); constructorIL.Emit(OpCodes.Ret); var methodBuilder = typeBuilder.DefineMethod( compareMethodGeneric.Name, compareMethodGeneric.Attributes & ~MethodAttributes.Abstract, compareMethodGeneric.CallingConvention, compareMethodGeneric.ReturnType, compareMethodGeneric.GetParameters().Select(p => p.ParameterType).ToArray() ); var methodBuilderIL = methodBuilder.GetILGenerator(); methodBuilderIL.Emit(OpCodes.Ldarg_0); methodBuilderIL.Emit(OpCodes.Ldfld, fieldBuilder); methodBuilderIL.Emit(OpCodes.Ldarg_1); methodBuilderIL.Emit(OpCodes.Box, genericType); methodBuilderIL.Emit(OpCodes.Ldarg_2); methodBuilderIL.Emit(OpCodes.Box, genericType); methodBuilderIL.Emit(OpCodes.Callvirt, compareMethod); methodBuilderIL.Emit(OpCodes.Ret); return GeneratedTypes.GetOrAdd(key, typeBuilder.CreateType()); } } } return type; } /// <summary> /// The CreateType method creates a new data class with a given set of public properties and returns the System.Type object for the newly created class. If a data class with an identical sequence of properties has already been created, the System.Type object for this class is returned. /// Data classes implement private instance variables and read/write property accessors for the specified properties.Data classes also override the Equals and GetHashCode members to implement by-value equality. /// Data classes are created in an in-memory assembly in the current application domain. All data classes inherit from <see cref="DynamicClass"/> and are given automatically generated names that should be considered private (the names will be unique within the application domain but not across multiple invocations of the application). Note that once created, a data class stays in memory for the lifetime of the current application domain. There is currently no way to unload a dynamically created data class. /// The dynamic expression parser uses the CreateClass methods to generate classes from data object initializers. This feature in turn is often used with the dynamic Select method to create projections. /// </summary> /// <param name="properties">The DynamicProperties</param> /// <param name="createParameterCtor">Create a constructor with parameters. Default set to true. Note that for Linq-to-Database objects, this needs to be set to false.</param> /// <returns>Type</returns> /// <example> /// <code> /// <![CDATA[ /// DynamicProperty[] props = new DynamicProperty[] { new DynamicProperty("Name", typeof(string)), new DynamicProperty("Birthday", typeof(DateTime)) }; /// Type type = DynamicClassFactory.CreateType(props); /// DynamicClass dynamicClass = (DynamicClass) Activator.CreateInstance(type)!; /// dynamicClass.SetDynamicPropertyValue("Name", "Albert"); /// dynamicClass.SetDynamicPropertyValue("Birthday", new DateTime(1879, 3, 14)); /// ]]> /// </code> /// </example> public static Type CreateType(IList<DynamicProperty> properties, bool createParameterCtor = true) { Check.HasNoNulls(properties); var key = GenerateKey(properties, createParameterCtor); // ReSharper disable once InconsistentlySynchronizedField if (!GeneratedTypes.TryGetValue(key, out var type)) { // We create only a single class at a time, through this lock. // Note that this is a variant of the double-checked locking. // It is safe because we are using a thread safe class. lock (GeneratedTypes) { return GeneratedTypes.GetOrAdd(key, _ => EmitType(properties, createParameterCtor)); } } return type; } private static Type EmitType(IList<DynamicProperty> properties, bool createParameterCtor) { var typeIndex = Interlocked.Increment(ref _index); var typeName = properties.Any() ? $"<>f__AnonymousType{typeIndex}`{properties.Count}" : $"<>f__AnonymousType{typeIndex}"; var typeBuilder = ModuleBuilder.DefineType(typeName, TypeAttributes.AnsiClass | TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoLayout | TypeAttributes.BeforeFieldInit, typeof(DynamicClass)); typeBuilder.SetCustomAttribute(CompilerGeneratedAttributeBuilder); var fieldBuilders = new FieldBuilder[properties.Count]; // There are two for-loops because we want to have all the getter methods before all the other methods for (int i = 0; i < properties.Count; i++) { var fieldName = properties[i].Name; var fieldType = properties[i].Type; // field fieldBuilders[i] = typeBuilder.DefineField($"<{fieldName}>i__Field", fieldType, FieldAttributes.Private | FieldAttributes.InitOnly); fieldBuilders[i].SetCustomAttribute(DebuggerBrowsableAttributeBuilder); PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(fieldName, PropertyAttributes.None, CallingConventions.HasThis, fieldType, Type.EmptyTypes); // getter MethodBuilder getter = typeBuilder.DefineMethod($"get_{fieldName}", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName, CallingConventions.HasThis, fieldType, null); getter.SetCustomAttribute(CompilerGeneratedAttributeBuilder); ILGenerator ilgeneratorGetter = getter.GetILGenerator(); ilgeneratorGetter.Emit(OpCodes.Ldarg_0); ilgeneratorGetter.Emit(OpCodes.Ldfld, fieldBuilders[i]); ilgeneratorGetter.Emit(OpCodes.Ret); propertyBuilder.SetGetMethod(getter); // setter MethodBuilder setter = typeBuilder.DefineMethod($"set_{fieldName}", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName, CallingConventions.HasThis, null, [fieldType]); setter.SetCustomAttribute(CompilerGeneratedAttributeBuilder); // workaround for path_to_url setter.DefineParameter(1, ParameterAttributes.In, properties[i].Name); ILGenerator ilgeneratorSetter = setter.GetILGenerator(); ilgeneratorSetter.Emit(OpCodes.Ldarg_0); ilgeneratorSetter.Emit(OpCodes.Ldarg_1); ilgeneratorSetter.Emit(OpCodes.Stfld, fieldBuilders[i]); ilgeneratorSetter.Emit(OpCodes.Ret); propertyBuilder.SetSetMethod(setter); } // ToString() MethodBuilder toString = typeBuilder.DefineMethod(nameof(ToString), MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, CallingConventions.HasThis, typeof(string), Type.EmptyTypes); toString.SetCustomAttribute(DebuggerHiddenAttributeBuilder); ILGenerator ilgeneratorToString = toString.GetILGenerator(); ilgeneratorToString.DeclareLocal(typeof(StringBuilder)); ilgeneratorToString.Emit(OpCodes.Newobj, StringBuilderCtor); ilgeneratorToString.Emit(OpCodes.Stloc_0); // Equals MethodBuilder equals = typeBuilder.DefineMethod(nameof(Equals), MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, CallingConventions.HasThis, typeof(bool), [typeof(object)]); equals.DefineParameter(1, ParameterAttributes.In, "value"); equals.SetCustomAttribute(DebuggerHiddenAttributeBuilder); ILGenerator ilgeneratorEquals = equals.GetILGenerator(); ilgeneratorEquals.DeclareLocal(typeBuilder.AsType()); ilgeneratorEquals.Emit(OpCodes.Ldarg_1); ilgeneratorEquals.Emit(OpCodes.Isinst, typeBuilder.AsType()); ilgeneratorEquals.Emit(OpCodes.Stloc_0); ilgeneratorEquals.Emit(OpCodes.Ldloc_0); // GetHashCode() MethodBuilder getHashCode = typeBuilder.DefineMethod(nameof(GetHashCode), MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, CallingConventions.HasThis, typeof(int), Type.EmptyTypes); getHashCode.SetCustomAttribute(DebuggerHiddenAttributeBuilder); ILGenerator ilgeneratorGetHashCode = getHashCode.GetILGenerator(); ilgeneratorGetHashCode.DeclareLocal(typeof(int)); if (properties.Count == 0) { ilgeneratorGetHashCode.Emit(OpCodes.Ldc_I4_0); } else { // As done by Roslyn // Note that initHash can vary, because string.GetHashCode() isn't "stable" for different compilation of the code int initHash = 0; for (int i = 0; i < properties.Count; i++) { initHash = unchecked(initHash * -1521134295 + fieldBuilders[i].Name.GetHashCode()); } // Note that the CSC seems to generate a different seed for every anonymous class ilgeneratorGetHashCode.Emit(OpCodes.Ldc_I4, initHash); } Label equalsLabel = ilgeneratorEquals.DefineLabel(); for (var i = 0; i < properties.Count; i++) { var fieldName = properties[i].Name; var fieldType = properties[i].Type; var equalityComparerT = EqualityComparer.MakeGenericType(fieldType); // Equals() MethodInfo equalityComparerTDefault = equalityComparerT.GetMethod("get_Default", BindingFlags.Static | BindingFlags.Public)!; MethodInfo equalityComparerTEquals = equalityComparerT.GetMethod(nameof(EqualityComparer.Equals), BindingFlags.Instance | BindingFlags.Public, null, [fieldType, fieldType], null)!; // Illegal one-byte branch at position: 9. Requested branch was: 143. // So replace OpCodes.Brfalse_S to OpCodes.Brfalse ilgeneratorEquals.Emit(OpCodes.Brfalse, equalsLabel); ilgeneratorEquals.Emit(OpCodes.Call, equalityComparerTDefault); ilgeneratorEquals.Emit(OpCodes.Ldarg_0); ilgeneratorEquals.Emit(OpCodes.Ldfld, fieldBuilders[i]); ilgeneratorEquals.Emit(OpCodes.Ldloc_0); ilgeneratorEquals.Emit(OpCodes.Ldfld, fieldBuilders[i]); ilgeneratorEquals.Emit(OpCodes.Callvirt, equalityComparerTEquals); // GetHashCode(); MethodInfo equalityComparerTGetHashCode = equalityComparerT.GetMethod(nameof(EqualityComparer.GetHashCode), BindingFlags.Instance | BindingFlags.Public, null, [fieldType], null)!; ilgeneratorGetHashCode.Emit(OpCodes.Stloc_0); ilgeneratorGetHashCode.Emit(OpCodes.Ldc_I4, -1521134295); ilgeneratorGetHashCode.Emit(OpCodes.Ldloc_0); ilgeneratorGetHashCode.Emit(OpCodes.Mul); ilgeneratorGetHashCode.Emit(OpCodes.Call, equalityComparerTDefault); ilgeneratorGetHashCode.Emit(OpCodes.Ldarg_0); ilgeneratorGetHashCode.Emit(OpCodes.Ldfld, fieldBuilders[i]); ilgeneratorGetHashCode.Emit(OpCodes.Callvirt, equalityComparerTGetHashCode); ilgeneratorGetHashCode.Emit(OpCodes.Add); // ToString(); ilgeneratorToString.Emit(OpCodes.Ldloc_0); ilgeneratorToString.Emit(OpCodes.Ldstr, i == 0 ? $"{{ {fieldName} = " : $", {fieldName} = "); ilgeneratorToString.Emit(OpCodes.Callvirt, StringBuilderAppendString); ilgeneratorToString.Emit(OpCodes.Pop); ilgeneratorToString.Emit(OpCodes.Ldloc_0); ilgeneratorToString.Emit(OpCodes.Ldarg_0); ilgeneratorToString.Emit(OpCodes.Ldfld, fieldBuilders[i]); ilgeneratorToString.Emit(OpCodes.Box, properties[i].Type); ilgeneratorToString.Emit(OpCodes.Callvirt, StringBuilderAppendObject); ilgeneratorToString.Emit(OpCodes.Pop); } // Only create the default and with params constructor when there are any params. // Otherwise default constructor is not needed because it matches the default // one provided by the runtime when no constructor is present if (createParameterCtor && properties.Any()) { // .ctor default ConstructorBuilder constructorDef = typeBuilder.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig, CallingConventions.HasThis, Type.EmptyTypes); constructorDef.SetCustomAttribute(DebuggerHiddenAttributeBuilder); ILGenerator ilgeneratorConstructorDef = constructorDef.GetILGenerator(); ilgeneratorConstructorDef.Emit(OpCodes.Ldarg_0); ilgeneratorConstructorDef.Emit(OpCodes.Call, ObjectCtor); ilgeneratorConstructorDef.Emit(OpCodes.Ret); // .ctor with params var types = properties.Select(p => p.Type).ToArray(); ConstructorBuilder constructor = typeBuilder.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig, CallingConventions.HasThis, types); constructor.SetCustomAttribute(DebuggerHiddenAttributeBuilder); ILGenerator ilgeneratorConstructor = constructor.GetILGenerator(); ilgeneratorConstructor.Emit(OpCodes.Ldarg_0); ilgeneratorConstructor.Emit(OpCodes.Call, ObjectCtor); for (var i = 0; i < properties.Count; i++) { constructor.DefineParameter(i + 1, ParameterAttributes.None, properties[i].Name); ilgeneratorConstructor.Emit(OpCodes.Ldarg_0); if (i == 0) { ilgeneratorConstructor.Emit(OpCodes.Ldarg_1); } else if (i == 1) { ilgeneratorConstructor.Emit(OpCodes.Ldarg_2); } else if (i == 2) { ilgeneratorConstructor.Emit(OpCodes.Ldarg_3); } else if (i < 255) { ilgeneratorConstructor.Emit(OpCodes.Ldarg_S, (byte)(i + 1)); } else { // Ldarg uses an ushort, but the Emit only accepts short, so we use a unchecked(...), cast to short and let the CLR interpret it as ushort. ilgeneratorConstructor.Emit(OpCodes.Ldarg, unchecked((short)(i + 1))); } ilgeneratorConstructor.Emit(OpCodes.Stfld, fieldBuilders[i]); } ilgeneratorConstructor.Emit(OpCodes.Ret); } // Equals() if (properties.Count == 0) { ilgeneratorEquals.Emit(OpCodes.Ldnull); ilgeneratorEquals.Emit(OpCodes.Ceq); ilgeneratorEquals.Emit(OpCodes.Ldc_I4_0); ilgeneratorEquals.Emit(OpCodes.Ceq); } else { ilgeneratorEquals.Emit(OpCodes.Ret); ilgeneratorEquals.MarkLabel(equalsLabel); ilgeneratorEquals.Emit(OpCodes.Ldc_I4_0); } ilgeneratorEquals.Emit(OpCodes.Ret); // GetHashCode() ilgeneratorGetHashCode.Emit(OpCodes.Stloc_0); ilgeneratorGetHashCode.Emit(OpCodes.Ldloc_0); ilgeneratorGetHashCode.Emit(OpCodes.Ret); // ToString() ilgeneratorToString.Emit(OpCodes.Ldloc_0); ilgeneratorToString.Emit(OpCodes.Ldstr, properties.Count == 0 ? "{ }" : " }"); ilgeneratorToString.Emit(OpCodes.Callvirt, StringBuilderAppendString); ilgeneratorToString.Emit(OpCodes.Pop); ilgeneratorToString.Emit(OpCodes.Ldloc_0); ilgeneratorToString.Emit(OpCodes.Callvirt, ObjectToString); ilgeneratorToString.Emit(OpCodes.Ret); EmitEqualityOperators(typeBuilder, equals); return typeBuilder.CreateType(); } private static void EmitEqualityOperators(TypeBuilder typeBuilder, MethodBuilder equals) { // Define the '==' operator MethodBuilder equalityOperator = typeBuilder.DefineMethod( "op_Equality", MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.SpecialName | MethodAttributes.HideBySig, typeof(bool), [typeBuilder.AsType(), typeBuilder.AsType()]); ILGenerator ilgeneratorEqualityOperator = equalityOperator.GetILGenerator(); // if (left == null || right == null) return ReferenceEquals(left, right); Label endLabel = ilgeneratorEqualityOperator.DefineLabel(); ilgeneratorEqualityOperator.Emit(OpCodes.Ldarg_0); ilgeneratorEqualityOperator.Emit(OpCodes.Brfalse_S, endLabel); ilgeneratorEqualityOperator.Emit(OpCodes.Ldarg_1); ilgeneratorEqualityOperator.Emit(OpCodes.Brfalse_S, endLabel); // return left.Equals(right); ilgeneratorEqualityOperator.Emit(OpCodes.Ldarg_0); ilgeneratorEqualityOperator.Emit(OpCodes.Ldarg_1); ilgeneratorEqualityOperator.Emit(OpCodes.Callvirt, equals); ilgeneratorEqualityOperator.Emit(OpCodes.Ret); // Return false if one is null ilgeneratorEqualityOperator.MarkLabel(endLabel); ilgeneratorEqualityOperator.Emit(OpCodes.Ldarg_0); ilgeneratorEqualityOperator.Emit(OpCodes.Ldarg_1); ilgeneratorEqualityOperator.Emit(OpCodes.Call, typeof(object).GetMethod("ReferenceEquals")!); ilgeneratorEqualityOperator.Emit(OpCodes.Ret); // Define the '!=' operator MethodBuilder inequalityOperator = typeBuilder.DefineMethod( "op_Inequality", MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.SpecialName | MethodAttributes.HideBySig, typeof(bool), [typeBuilder.AsType(), typeBuilder.AsType()]); ILGenerator ilNeq = inequalityOperator.GetILGenerator(); // return !(left == right); ilNeq.Emit(OpCodes.Ldarg_0); ilNeq.Emit(OpCodes.Ldarg_1); ilNeq.Emit(OpCodes.Call, equalityOperator); ilNeq.Emit(OpCodes.Ldc_I4_0); ilNeq.Emit(OpCodes.Ceq); ilNeq.Emit(OpCodes.Ret); } /// <summary> /// Generates the key. /// Anonymous classes are generics based. The generic classes are distinguished by number of parameters and name of parameters. /// The specific types of the parameters are the generic arguments. /// </summary> /// <param name="dynamicProperties">The dynamic properties.</param> /// <param name="createParameterCtor">if set to <c>true</c> [create parameter ctor].</param> /// <returns></returns> private static string GenerateKey(IEnumerable<DynamicProperty> dynamicProperties, bool createParameterCtor) { // We recreate this by creating a fullName composed of all the property names and types, separated by a "|". // And append and extra field depending on createParameterCtor. return $"{string.Join("|", dynamicProperties.Select(p => Escape(p.Name) + "~" + p.Type.FullName).ToArray())}_{(createParameterCtor ? "c" : string.Empty)}"; } private static string Escape(string str) { // We escape the \ with \\, so that we can safely escape the "|" (that we use as a separator) with "\|" str = str.Replace(@"\", @"\\"); str = str.Replace(@"|", @"\|"); return str; } /// <summary> /// Used for unit-testing /// </summary> internal static void ClearGeneratedTypes() { lock (GeneratedTypes) { GeneratedTypes.Clear(); } } } #endif ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/DynamicClassFactory.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
4,907
```smalltalk using System.Linq.Dynamic.Core.Validation; using System.Reflection; namespace System.Linq.Dynamic.Core; /// <summary> /// Default implementation. /// </summary> /// <seealso cref="IQueryableAnalyzer" /> public class DefaultQueryableAnalyzer : IQueryableAnalyzer { /// <inheritdoc cref="IQueryableAnalyzer.SupportsLinqToObjects"/> public bool SupportsLinqToObjects(IQueryable query, IQueryProvider? provider = null) { Check.NotNull(query, nameof(query)); provider = provider ?? query.Provider; Type providerType = provider.GetType(); Type baseType = providerType.GetTypeInfo().BaseType!; #if NET35 bool isLinqToObjects = baseType.FullName!.Contains("EnumerableQuery"); #else bool isLinqToObjects = baseType == typeof(EnumerableQuery); #endif if (!isLinqToObjects) { // Support for path_to_url version 1.0.1 and up if (providerType.Name.StartsWith("QueryTranslatorProvider")) { try { var property = providerType.GetProperty("OriginalProvider"); if (property != null) { return property.GetValue(provider, null) is IQueryProvider originalProvider && SupportsLinqToObjects(query, originalProvider); } return SupportsLinqToObjects(query); } catch { return false; } } // Support for path_to_url ExpandableQuery if (providerType.Name.StartsWith("ExpandableQuery")) { try { var property = query.GetType().GetProperty("InnerQuery", BindingFlags.NonPublic | BindingFlags.Instance); if (property != null) { return property.GetValue(query, null) is IQueryable innerQuery && SupportsLinqToObjects(innerQuery, provider); } return SupportsLinqToObjects(query); } catch { return false; } } } return isLinqToObjects; } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/DefaultQueryableAnalyzer.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
404
```smalltalk using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq.Dynamic.Core.Config; using System.Linq.Dynamic.Core.CustomTypeProviders; using System.Linq.Dynamic.Core.Parser; using System.Linq.Dynamic.Core.Util.Cache; namespace System.Linq.Dynamic.Core; /// <summary> /// Configuration class for System.Linq.Dynamic.Core. /// </summary> public class ParsingConfig { private IDynamicLinkCustomTypeProvider? _customTypeProvider; private IExpressionPromoter? _expressionPromoter; private IQueryableAnalyzer? _queryableAnalyzer; /// <summary> /// Default ParsingConfig /// </summary> public static ParsingConfig Default { get; } = new(); /// <summary> /// Default ParsingConfig for EntityFramework Core 2.1 and higher /// </summary> public static ParsingConfig DefaultEFCore21 { get; } = new() { EvaluateGroupByAtDatabase = true }; /// <summary> /// Default ParsingConfig for CosmosDb /// </summary> public static ParsingConfig DefaultCosmosDb { get; } = new() { RenameEmptyParameterExpressionNames = true }; /// <summary> /// Gets or sets if parameter, method, and properties resolution should be case-sensitive or not. /// /// Default value is <c>false</c>. /// </summary> public bool IsCaseSensitive { get; set; } /// <summary> /// Gets or sets the <see cref="IDynamicLinkCustomTypeProvider"/>. /// </summary> public IDynamicLinkCustomTypeProvider? CustomTypeProvider { get { #if !(UAP10_0 || NETSTANDARD) // Only use DefaultDynamicLinqCustomTypeProvider for full .NET Framework and .NET Core App 2.x and higher. return _customTypeProvider ??= new DefaultDynamicLinqCustomTypeProvider(this); #else return _customTypeProvider; #endif } set { _customTypeProvider = value; } } /// <summary> /// Load additional assemblies from the current domain base directory. /// Note: only used when full .NET Framework and .NET Core App 2.x and higher. /// /// Default value is <c>false</c>. /// </summary> public bool LoadAdditionalAssembliesFromCurrentDomainBaseDirectory { get; set; } /// <summary> /// Gets or sets the <see cref="IExpressionPromoter"/>. /// </summary> public IExpressionPromoter ExpressionPromoter { get => _expressionPromoter ??= new ExpressionPromoter(this); set { // ReSharper disable once RedundantCheckBeforeAssignment if (_expressionPromoter != value) { _expressionPromoter = value; } } } /// <summary> /// Gets or sets the <see cref="IQueryableAnalyzer"/>. /// </summary> public IQueryableAnalyzer QueryableAnalyzer { get { return _queryableAnalyzer ??= new DefaultQueryableAnalyzer(); } set { // ReSharper disable once RedundantCheckBeforeAssignment if (_queryableAnalyzer != value) { _queryableAnalyzer = value; } } } /// <summary> /// Determines if the context keywords (it, parent, and root) are valid and usable inside a Dynamic Linq string expression. /// Does not affect the usability of the equivalent context symbols ($, ^ and ~). /// /// Default value is <c>false</c>. /// </summary> public bool AreContextKeywordsEnabled { get; set; } = true; /// <summary> /// Gets or sets a value indicating whether the EntityFramework version supports evaluating GroupBy at database level. /// See path_to_url#linq-groupby-translation /// Remark: when this setting is set to <c>true</c>, make sure to supply this ParsingConfig as first parameter on the extension methods. /// /// Default value is <c>false</c>. /// </summary> public bool EvaluateGroupByAtDatabase { get; set; } /// <summary> /// Use Parameterized Names in generated dynamic SQL query. /// See path_to_url /// /// Default value is <c>false</c>. /// </summary> public bool UseParameterizedNamesInDynamicQuery { get; set; } /// <summary> /// Allows the New() keyword to evaluate any available Type. /// /// Default value is <c>false</c>. /// </summary> public bool AllowNewToEvaluateAnyType { get; set; } /// <summary> /// Renames the (Typed)ParameterExpression empty Name to the correct supplied name from `it`. /// /// Default value is <c>false</c>. /// </summary> public bool RenameParameterExpression { get; set; } /// <summary> /// Prevents any System.Linq.Expressions.ParameterExpression.Name value from being empty by substituting a random 16 character word. /// /// Default value is <c>false</c>. /// </summary> public bool RenameEmptyParameterExpressionNames { get; set; } /// <summary> /// By default, when a member is not found in a type and the type has a string based index accessor it will be parsed as an index accessor. /// Use this flag to disable this behaviour and have parsing fail when parsing an expression where a member access on a non-existing member happens. /// /// Default value is <c>false</c>. /// </summary> public bool DisableMemberAccessToIndexAccessorFallback { get; set; } /// <summary> /// By default, finding types by a simple name is not supported. /// Use this flag to use the CustomTypeProvider to resolve types by a simple name like "Employee" instead of "MyDatabase.Entities.Employee". /// Note that a first matching type is returned and this functionality needs to scan all types from all assemblies, so use with caution. /// /// Default value is <c>false</c>. /// </summary> public bool ResolveTypesBySimpleName { get; set; } /// <summary> /// Support enumeration-types from the System namespace in mscorlib. An example could be "StringComparison". /// /// Default value is <c>true</c>. /// </summary> public bool SupportEnumerationsFromSystemNamespace { get; set; } = true; /// <summary> /// By default, a DateTime (like 'Fri, 10 May 2019 11:03:17 GMT') is parsed as local time. /// Use this flag to parse all DateTime strings as UTC. /// /// Default value is <c>false</c>. /// </summary> public bool DateTimeIsParsedAsUTC { get; set; } /// <summary> /// The number parsing culture. /// /// Default value is CultureInfo.InvariantCulture /// </summary> public CultureInfo? NumberParseCulture { get; set; } = CultureInfo.InvariantCulture; /// <summary> /// Additional TypeConverters /// </summary> public IDictionary<Type, TypeConverter>? TypeConverters { get; set; } /// <summary> /// When using the NullPropagating function np(...), use a "default value" for non-nullable value types instead of "null value". /// /// Default value is <c>false</c>. /// </summary> public bool NullPropagatingUseDefaultValueForNonNullableValueTypes { get; set; } /// <summary> /// Support casting to a full qualified type using a string (double-quoted value). /// <code> /// var result = queryable.Select($"\"System.DateTime\"(LastUpdate)"); /// </code> /// /// Default value is <c>true</c>. /// </summary> public bool SupportCastingToFullyQualifiedTypeAsString { get; set; } = true; /// <summary> /// When the type and property have the same name the parser takes the property instead of type when this setting is set to <c>true</c>. /// This setting is also used for calling ExtensionMethods. /// /// Default value is <c>true</c>. /// </summary> public bool PrioritizePropertyOrFieldOverTheType { get; set; } = true; /// <summary> /// Support a "." in a property-name. Used in the 'new (a.b as a.b)' syntax. /// /// Default value is <c>false</c>. /// </summary> public bool SupportDotInPropertyNames { get; set; } /// <summary> /// Disallows the New() keyword to be used to construct a class. /// /// Default value is <c>false</c>. /// </summary> public bool DisallowNewKeyword { get; set; } /// <summary> /// Caches constant expressions to enhance performance. Periodic cleanup is performed to manage cache size, governed by this configuration. /// </summary> public CacheConfig? ConstantExpressionCacheConfig { get; set; } /// <summary> /// Converts typeof(object) to the correct type to allow comparison (Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan and LessThanEqual). /// /// Default value is <c>false</c>. /// /// When set to <c>true</c>, the following code will work correct: /// <example> /// <code> /// <![CDATA[ /// class Person /// { /// public string Name { get; set; } /// public object Age { get; set; } /// } /// /// var persons = new[] /// { /// new Person { Name = "Foo", Age = 99 }, /// new Person { Name = "Bar", Age = 33 } /// }.AsQueryable(); /// /// var config = new ParsingConfig /// { /// ConvertObjectToSupportComparison = true /// }; /// /// var results = persons.Where(config, "Age > 50").ToList(); /// ]]> /// </code> /// </example> /// </summary> public bool ConvertObjectToSupportComparison { get; set; } /// <summary> /// Defines the type of string literal parsing that will be performed. /// Default value is <c>StringLiteralParsingType.Default</c>. /// </summary> public StringLiteralParsingType StringLiteralParsing { get; set; } = StringLiteralParsingType.Default; } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/ParsingConfig.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
2,275
```smalltalk using System.Collections; using System.Collections.Generic; using System.Globalization; namespace System.Linq.Dynamic.Core { /// <summary> /// The result of a call to a <see cref="DynamicQueryableExtensions"/>.GroupByMany() overload. /// </summary> public class GroupResult { /// <summary> /// The key value of the group. /// </summary> #if NET35 || SILVERLIGHT public object Key { get; internal set; } = null!; #else public dynamic Key { get; internal set; } = null!; #endif /// <summary> /// The number of resulting elements in the group. /// </summary> public int Count { get; internal set; } /// <summary> /// The resulting elements in the group. /// </summary> public IEnumerable Items { get; internal set; } /// <summary> /// The resulting subgroups in the group. /// </summary> public IEnumerable<GroupResult>? Subgroups { get; internal set; } /// <summary> /// Returns a <see cref="System.String" /> showing the key of the group and the number of items in the group. /// </summary> /// <returns> /// A <see cref="System.String" /> that represents this instance. /// </returns> public override string ToString() { return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", ((object)Key).ToString(), Count); } } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/GroupResult.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
317
```smalltalk using System.Linq.Expressions; namespace System.Linq.Dynamic.Core; /// <summary> /// Extensibility point: If you want to modify expanded queries before executing them /// set your own functionality to override empty QueryOptimizer /// </summary> public class ExtensibilityPoint { /// <summary> /// Place to optimize your queries. Example: Add a reference to Nuget package Linq.Expression.Optimizer /// and in your program initializers set Extensibility.QueryOptimizer = ExpressionOptimizer.visit; /// </summary> public static Func<Expression, Expression> QueryOptimizer = e => e; } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/ExtensibilityPoint.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
125
```smalltalk #if !UAP10_0 && !NET35 using System.Collections.Generic; using System.Dynamic; using System.Reflection; namespace System.Linq.Dynamic.Core; /// <summary> /// Provides a base class for dynamic objects. /// /// In addition to the methods defined here, the following items are added using reflection: /// - default constructor /// - constructor with all the properties as parameters (if not linq-to-entities) /// - all properties (also with getter and setters) /// - ToString() method /// - Equals() method /// - GetHashCode() method /// </summary> public abstract class DynamicClass : DynamicObject { private Dictionary<string, object?>? _propertiesDictionary; private Dictionary<string, object?> Properties { get { if (_propertiesDictionary == null) { _propertiesDictionary = new(); foreach (PropertyInfo pi in GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { int parameters = pi.GetIndexParameters().Length; if (parameters > 0) { // The property is an indexer, skip this. continue; } _propertiesDictionary.Add(pi.Name, pi.GetValue(this, null)); } } return _propertiesDictionary; } } /// <summary> /// Gets the dynamic property by name. /// </summary> /// <typeparam name="T">The type.</typeparam> /// <param name="propertyName">Name of the property.</param> /// <returns>T</returns> public T? GetDynamicPropertyValue<T>(string propertyName) { var type = GetType(); var propInfo = type.GetProperty(propertyName); return (T?)propInfo?.GetValue(this, null); } /// <summary> /// Gets the dynamic property value by name. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <returns>value</returns> public object? GetDynamicPropertyValue(string propertyName) { return GetDynamicPropertyValue<object>(propertyName); } /// <summary> /// Sets the dynamic property value by name. /// </summary> /// <typeparam name="T">The type.</typeparam> /// <param name="propertyName">Name of the property.</param> /// <param name="value">The value.</param> public void SetDynamicPropertyValue<T>(string propertyName, T value) { var type = GetType(); var propInfo = type.GetProperty(propertyName); propInfo?.SetValue(this, value, null); } /// <summary> /// Sets the dynamic property value by name. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="value">The value.</param> public void SetDynamicPropertyValue(string propertyName, object value) { SetDynamicPropertyValue<object>(propertyName, value); } /// <summary> /// Gets or sets the <see cref="object"/> with the specified name. /// </summary> /// <value>The <see cref="object"/>.</value> /// <param name="name">The name.</param> /// <returns>Value from the property.</returns> public object? this[string name] { get { return Properties.TryGetValue(name, out object? result) ? result : null; } set { if (Properties.ContainsKey(name)) { Properties[name] = value; } else { Properties.Add(name, value); } } } /// <summary> /// Returns the enumeration of all dynamic member names. /// </summary> /// <returns> /// A sequence that contains dynamic member names. /// </returns> public override IEnumerable<string> GetDynamicMemberNames() { return Properties.Keys; } /// <summary> /// Provides the implementation for operations that get member values. Classes derived from the <see cref="T:System.Dynamic.DynamicObject" /> class can override this method to specify dynamic behavior for operations such as getting a value for a property. /// </summary> /// <param name="binder">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the Console.WriteLine(sampleObject.SampleProperty) statement, where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject" /> class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param> /// <param name="result">The result of the get operation. For example, if the method is called for a property, you can assign the property value to <paramref name="result" />.</param> /// <returns> /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a run-time exception is thrown.) /// </returns> public override bool TryGetMember(GetMemberBinder binder, out object? result) { return Properties.TryGetValue(binder.Name, out result); } /// <summary> /// Provides the implementation for operations that set member values. Classes derived from the <see cref="T:System.Dynamic.DynamicObject" /> class can override this method to specify dynamic behavior for operations such as setting a value for a property. /// </summary> /// <param name="binder">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member to which the value is being assigned. For example, for the statement sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject" /> class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param> /// <param name="value">The value to set to the member. For example, for sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject" /> class, the <paramref name="value" /> is "Test".</param> /// <returns> /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.) /// </returns> public override bool TrySetMember(SetMemberBinder binder, object? value) { string name = binder.Name; if (Properties.ContainsKey(name)) { Properties[name] = value; } else { Properties.Add(name, value); } return true; } } #endif ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/DynamicClass.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
1,435
```smalltalk namespace System.Linq.Dynamic.Core { /// <summary> /// DynamicProperty /// </summary> public class DynamicProperty { /// <summary> /// Initializes a new instance of the <see cref="DynamicProperty"/> class. /// </summary> /// <param name="name">The name from the property.</param> /// <param name="type">The type from the property.</param> public DynamicProperty(string name, Type type) { Name = name; Type = type; } /// <summary> /// Gets the name from the property. /// </summary> /// <value> /// The name from the property. /// </value> public string Name { get; } /// <summary> /// Gets the type from the property. /// </summary> /// <value> /// The type from the property. /// </value> public Type Type { get; } } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/DynamicProperty.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
207
```smalltalk #if UAP10_0 using System.Collections.Generic; using System.Dynamic; namespace System.Linq.Dynamic.Core; /// <summary> /// Provides a base class for dynamic objects for UAP10_0. /// </summary> public class DynamicClass : DynamicObject { private readonly Dictionary<string, object> _properties = new(); /// <summary> /// Initializes a new instance of the <see cref="DynamicClass"/> class. /// </summary> /// <param name="propertylist">The propertylist.</param> public DynamicClass(params KeyValuePair<string, object>[] propertylist) { foreach (var kvp in propertylist) { _properties.Add(kvp.Key, kvp.Value); } } /// <summary> /// Gets or sets the <see cref="object"/> with the specified name. /// </summary> /// <value> /// The <see cref="object"/>. /// </value> /// <param name="name">The name.</param> /// <returns>Value from the property.</returns> public object this[string name] { get { if (_properties.TryGetValue(name, out object result)) { return result; } return null; } set { if (_properties.ContainsKey(name)) { _properties[name] = value; } else { _properties.Add(name, value); } } } /// <summary> /// Returns the enumeration of all dynamic member names. /// </summary> /// <returns> /// A sequence that contains dynamic member names. /// </returns> public override IEnumerable<string> GetDynamicMemberNames() { return _properties.Keys; } /// <summary> /// Provides the implementation for operations that get member values. Classes derived from the <see cref="T:System.Dynamic.DynamicObject" /> class can override this method to specify dynamic behavior for operations such as getting a value for a property. /// </summary> /// <param name="binder">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the Console.WriteLine(sampleObject.SampleProperty) statement, where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject" /> class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param> /// <param name="result">The result of the get operation. For example, if the method is called for a property, you can assign the property value to <paramref name="result" />.</param> /// <returns> /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a run-time exception is thrown.) /// </returns> public override bool TryGetMember(GetMemberBinder binder, out object result) { var name = binder.Name; _properties.TryGetValue(name, out result); return true; } /// <summary> /// Provides the implementation for operations that set member values. Classes derived from the <see cref="T:System.Dynamic.DynamicObject" /> class can override this method to specify dynamic behavior for operations such as setting a value for a property. /// </summary> /// <param name="binder">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member to which the value is being assigned. For example, for the statement sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject" /> class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param> /// <param name="value">The value to set to the member. For example, for sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject" /> class, the <paramref name="value" /> is "Test".</param> /// <returns> /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.) /// </returns> public override bool TrySetMember(SetMemberBinder binder, object value) { string name = binder.Name; if (_properties.ContainsKey(name)) { _properties[name] = value; } else { _properties.Add(name, value); } return true; } } #endif ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/DynamicClass.uap.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
1,004
```smalltalk #if NET35 namespace System.Linq.Dynamic.Core; /// <summary> /// Provides a base class for dynamic objects for Net 3.5 /// </summary> public abstract class DynamicClass { /// <summary> /// Gets the dynamic property by name. /// </summary> /// <typeparam name="T">The type.</typeparam> /// <param name="propertyName">Name of the property.</param> /// <returns>T</returns> public T? GetDynamicPropertyValue<T>(string propertyName) { var type = GetType(); var propInfo = type.GetProperty(propertyName); return (T?)propInfo?.GetValue(this, null); } /// <summary> /// Gets the dynamic property value by name. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <returns>value</returns> public object? GetDynamicPropertyValue(string propertyName) { return GetDynamicPropertyValue<object>(propertyName); } /// <summary> /// Sets the dynamic property value by name. /// </summary> /// <typeparam name="T">The type.</typeparam> /// <param name="propertyName">Name of the property.</param> /// <param name="value">The value.</param> public void SetDynamicPropertyValue<T>(string propertyName, T value) { var type = GetType(); var propInfo = type.GetProperty(propertyName); propInfo?.SetValue(this, value, null); } /// <summary> /// Sets the dynamic property value by name. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="value">The value.</param> public void SetDynamicPropertyValue(string propertyName, object value) { SetDynamicPropertyValue<object>(propertyName, value); } } #endif ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/DynamicClass.net35.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
388
```smalltalk namespace System.Linq.Dynamic.Core; internal static class Res { public const string AmbiguousConstructorInvocation = "Ambiguous invocation of '{0}' constructor"; public const string AmbiguousIndexerInvocation = "Ambiguous invocation of indexer in type '{0}'"; public const string AmbiguousMethodInvocation = "Ambiguous invocation of method '{0}' in type '{1}'"; public const string ArgsIncompatibleWithLambda = "Argument list incompatible with lambda expression"; public const string BinaryCharExpected = "Binary character expected"; public const string BothTypesConvertToOther = "Both of the types '{0}' and '{1}' convert to the other"; public const string CannotConvertValue = "A value of type '{0}' cannot be converted to type '{1}'"; public const string CannotIndexMultiDimArray = "Indexing of multi-dimensional arrays is not supported"; public const string CloseBracketExpected = "']' expected"; public const string CloseBracketOrCommaExpected = "']' or ',' expected"; public const string CloseParenOrCommaExpected = "')' or ',' expected"; public const string CloseParenOrOperatorExpected = "')' or operator expected"; public const string ColonExpected = "':' expected"; public const string DigitExpected = "Digit expected"; public const string DotExpected = "'.' expected"; public const string DotOrOpenParenExpected = "'.' or '(' expected"; public const string DotOrOpenParenOrStringLiteralExpected = "'.' or '(' or string literal expected"; public const string DynamicExpandoObjectIsNotSupported = "Dynamic / ExpandoObject is not supported in .NET 3.5, UAP and .NETStandard 1.3"; public const string DuplicateIdentifier = "The identifier '{0}' was defined more than once"; public const string EnumTypeNotFound = "Enum type '{0}' not found"; public const string EnumValueExpected = "Enum value expected"; public const string EnumValueNotDefined = "Enum value '{0}' is not defined in enum type '{1}'"; public const string ExpressionExpected = "Expression expected"; public const string ExpressionTypeMismatch = "Expression of type '{0}' expected"; public const string FirstExprMustBeBool = "The first expression must be of type 'Boolean'"; public const string FunctionRequiresOneArg = "The '{0}' function requires one argument"; public const string FunctionRequiresOneNotNullArg = "The '{0}' function requires one argument which is not null."; public const string FunctionRequiresNotNullArgOfType = "The '{0}' function requires the {1}argument to be not null and of type {2}."; public const string FunctionRequiresOneOrTwoArgs = "The '{0}' function requires 1 or 2 arguments"; public const string HexCharExpected = "Hexadecimal character expected"; public const string IQueryableProviderNotAsync = "The provider for the source IQueryable doesn't implement IAsyncQueryProvider/IDbAsyncQueryProvider. Only providers that implement IAsyncQueryProvider/IDbAsyncQueryProvider can be used for Entity Framework asynchronous operations."; public const string IdentifierExpected = "Identifier expected"; public const string IdentifierImplementingInterfaceExpected = "Identifier implementing interface '{0}' expected"; public const string IifRequiresThreeArgs = "The 'iif' function requires three arguments"; public const string IncompatibleOperand = "Operator '{0}' incompatible with operand type '{1}'"; public const string IncompatibleOperands = "Operator '{0}' incompatible with operand types '{1}' and '{2}'"; public const string IncompatibleTypes = "Types '{0}' and '{1}' are incompatible"; public const string InvalidBinaryIntegerLiteral = "Invalid binary integer literal '{0}'"; public const string InvalidCharacter = "Syntax error '{0}'"; public const string InvalidCharacterLiteral = "Character literal must contain exactly one character"; public const string InvalidIndex = "Array index must be an integer expression"; public const string InvalidIntegerLiteral = "Invalid integer literal '{0}'"; public const string InvalidIntegerQualifier = "Invalid integer literal qualifier '{0}'"; public const string InvalidRealLiteral = "Invalid real literal '{0}'"; public const string InvalidStringQuoteCharacter = "An escaped string should start with a double (\") or a single (') quote."; public const string InvalidStringLength = "String '{0}' should have at least {1} characters."; public const string IsNullRequiresTwoArgs = "The 'isnull' function requires two arguments"; public const string MethodIsVoid = "Method '{0}' in type '{1}' does not return a value"; public const string MethodsAreInaccessible = "Methods on type '{0}' are not accessible"; public const string MinusCannotBeAppliedToUnsignedInteger = "'-' cannot be applied to unsigned integers."; public const string MissingAsClause = "Expression is missing an 'as' clause"; public const string NeitherTypeConvertsToOther = "Neither of the types '{0}' and '{1}' converts to the other"; public const string NewOperatorIsNotAllowed = "Using the new operator is not allowed via the ParsingConfig."; public const string NoApplicableIndexer = "No applicable indexer exists in type '{0}'"; public const string NoApplicableMethod = "No applicable method '{0}' exists in type '{1}'"; public const string NoItInScope = "No 'it' is in scope"; public const string NoMatchingConstructor = "No matching constructor in type '{0}'"; public const string NoParentInScope = "No 'parent' is in scope"; public const string NoRootInScope = "No 'root' is in scope"; public const string NullPropagationRequiresCorrectArgs = "The 'np' (null-propagation) function requires 1 or 2 arguments"; public const string NullPropagationRequiresValidExpression = "The 'np' (null-propagation) function requires the first argument to be a MemberExpression, ParameterExpression or MethodCallExpression"; public const string OpenBracketExpected = "'[' expected"; public const string OpenCurlyParenExpected = "'{' expected"; public const string OpenParenExpected = "'(' expected"; public const string OpenParenOrIdentifierExpected = "'(' or Identifier expected"; public const string OutKeywordRequiresDiscard = "When using an out variable, a discard '_' is required."; public const string ParseExceptionFormat = "{0} (at index {1})"; public const string SyntaxError = "Syntax error"; public const string TokenExpected = "{0} expected"; public const string TypeHasNoNullableForm = "Type '{0}' has no nullable form"; public const string TypeNotFound = "Type '{0}' not found"; public const string UnexpectedUnclosedString = "Unexpected end of string with unclosed string at position {0} near '{1}'."; public const string UnexpectedUnrecognizedEscapeSequence = "Unexpected unrecognized escape sequence at position {0} near '{1}'."; public const string UnknownIdentifier = "Unknown identifier '{0}'"; public const string UnknownPropertyOrField = "No property or field '{0}' exists in type '{1}'"; public const string UnterminatedStringLiteral = "Unterminated string literal"; } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Res.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
1,526
```smalltalk namespace System.Linq.Dynamic.Core { /// <summary> /// PagedResult /// </summary> public class PagedResult { /// <summary> /// Gets or sets the queryable. /// </summary> /// <value> /// The queryable. /// </value> public IQueryable Queryable { get; set; } /// <summary> /// Gets or sets the current page. /// </summary> /// <value> /// The current page. /// </value> public int CurrentPage { get; set; } /// <summary> /// Gets or sets the page count. /// </summary> /// <value> /// The page count. /// </value> public int PageCount { get; set; } /// <summary> /// Gets or sets the size of the page. /// </summary> /// <value> /// The size of the page. /// </value> public int PageSize { get; set; } /// <summary> /// Gets or sets the row count. /// </summary> /// <value> /// The row count. /// </value> public int RowCount { get; set; } } /// <summary> /// PagedResult{TSource} /// </summary> /// <typeparam name="TSource">The type of the source.</typeparam> public class PagedResult<TSource> : PagedResult { /// <summary> /// Gets or sets the queryable. /// </summary> /// <value> /// The queryable. /// </value> public new IQueryable<TSource> Queryable { get; set; } } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/PagedResult.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
371
```smalltalk using JetBrains.Annotations; using System.Linq.Dynamic.Core.Parser; using System.Linq.Dynamic.Core.Util; using System.Linq.Dynamic.Core.Validation; using System.Linq.Expressions; namespace System.Linq.Dynamic.Core; /// <summary> /// Helper class to convert an expression into an LambdaExpression /// </summary> public static class DynamicExpressionParser { /// <summary> /// Parses an expression into a LambdaExpression. /// </summary> /// <param name="parsingConfig">The Configuration for the parsing.</param> /// <param name="createParameterCtor">if set to <c>true</c> then also create a constructor for all the parameters. Note that this doesn't work for Linq-to-Database entities.</param> /// <param name="resultType">Type of the result. If not specified, it will be generated dynamically.</param> /// <param name="expression">The expression.</param> /// <param name="values">An object array that contains zero or more objects which are used as replacement values.</param> /// <returns>The generated <see cref="LambdaExpression"/></returns> [PublicAPI] public static LambdaExpression ParseLambda(ParsingConfig? parsingConfig, bool createParameterCtor, Type? resultType, string expression, params object?[] values) { Check.NotEmpty(expression); var parser = new ExpressionParser(new ParameterExpression[0], expression, values, parsingConfig); return Expression.Lambda(parser.Parse(resultType, createParameterCtor)); } /// <summary> /// Parses an expression into a LambdaExpression. /// </summary> /// <param name="delegateType">The delegate type.</param> /// <param name="parsingConfig">The Configuration for the parsing.</param> /// <param name="createParameterCtor">if set to <c>true</c> then also create a constructor for all the parameters. Note that this doesn't work for Linq-to-Database entities.</param> /// <param name="resultType">Type of the result. If not specified, it will be generated dynamically.</param> /// <param name="expression">The expression.</param> /// <param name="values">An object array that contains zero or more objects which are used as replacement values.</param> /// <returns>The generated <see cref="LambdaExpression"/></returns> [PublicAPI] public static LambdaExpression ParseLambda(Type delegateType, ParsingConfig? parsingConfig, bool createParameterCtor, Type? resultType, string expression, params object?[] values) { Check.NotEmpty(expression); var parser = new ExpressionParser(new ParameterExpression[0], expression, values, parsingConfig); return Expression.Lambda(delegateType, parser.Parse(resultType, createParameterCtor)); } /// <summary> /// Parses an expression into a Typed Expression. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="parsingConfig">The Configuration for the parsing.</param> /// <param name="createParameterCtor">if set to <c>true</c> then also create a constructor for all the parameters. Note that this doesn't work for Linq-to-Database entities.</param> /// <param name="expression">The expression.</param> /// <param name="values">An object array that contains zero or more objects which are used as replacement values.</param> /// <returns>The generated <see cref="Expression"/></returns> [PublicAPI] public static Expression<Func<TResult>> ParseLambda<TResult>(ParsingConfig? parsingConfig, bool createParameterCtor, string expression, params object?[] values) { return (Expression<Func<TResult>>)ParseLambda(parsingConfig, createParameterCtor, typeof(TResult), expression, values); } /// <summary> /// Parses an expression into a Typed Expression. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="delegateType">The delegate type.</param> /// <param name="parsingConfig">The Configuration for the parsing.</param> /// <param name="createParameterCtor">if set to <c>true</c> then also create a constructor for all the parameters. Note that this doesn't work for Linq-to-Database entities.</param> /// <param name="expression">The expression.</param> /// <param name="values">An object array that contains zero or more objects which are used as replacement values.</param> /// <returns>The generated <see cref="Expression"/></returns> [PublicAPI] public static Expression<Func<TResult>> ParseLambda<TResult>(Type delegateType, ParsingConfig? parsingConfig, bool createParameterCtor, string expression, params object?[] values) { Check.NotNull(delegateType); return (Expression<Func<TResult>>)ParseLambda(delegateType, parsingConfig, createParameterCtor, typeof(TResult), expression, values); } /// <summary> /// Parses an expression into a LambdaExpression. /// </summary> /// <param name="parsingConfig">The Configuration for the parsing.</param> /// <param name="createParameterCtor">if set to <c>true</c> then also create a constructor for all the parameters. Note that this doesn't work for Linq-to-Database entities.</param> /// <param name="parameters">A array from ParameterExpressions.</param> /// <param name="resultType">Type of the result. If not specified, it will be generated dynamically.</param> /// <param name="expression">The expression.</param> /// <param name="values">An object array that contains zero or more objects which are used as replacement values.</param> /// <returns>The generated <see cref="LambdaExpression"/></returns> [PublicAPI] public static LambdaExpression ParseLambda(ParsingConfig? parsingConfig, bool createParameterCtor, ParameterExpression[] parameters, Type? resultType, string expression, params object?[]? values) { return ParseLambda(null, parsingConfig, createParameterCtor, parameters, resultType, expression, values); } /// <summary> /// Parses an expression into a LambdaExpression. /// </summary> /// <param name="delegateType">The delegate type.</param> /// <param name="parsingConfig">The Configuration for the parsing.</param> /// <param name="createParameterCtor">if set to <c>true</c> then also create a constructor for all the parameters. Note that this doesn't work for Linq-to-Database entities.</param> /// <param name="parameters">A array from ParameterExpressions.</param> /// <param name="resultType">Type of the result. If not specified, it will be generated dynamically.</param> /// <param name="expression">The expression.</param> /// <param name="values">An object array that contains zero or more objects which are used as replacement values.</param> /// <returns>The generated <see cref="LambdaExpression"/></returns> [PublicAPI] public static LambdaExpression ParseLambda(Type? delegateType, ParsingConfig? parsingConfig, bool createParameterCtor, ParameterExpression[] parameters, Type? resultType, string expression, params object?[]? values) { Check.HasNoNulls(parameters); Check.NotEmpty(expression); var parser = new ExpressionParser(parameters, expression, values, parsingConfig); var parsedExpression = parser.Parse(resultType, createParameterCtor); if (parsedExpression is LambdaExpression lambdaExpression) { return lambdaExpression; } if (parsingConfig is { RenameParameterExpression: true } && parameters.Length == 1) { var renamer = new ParameterExpressionRenamer(parser.LastLambdaItName); parsedExpression = renamer.Rename(parsedExpression, out var newParameterExpression); return delegateType == null ? Expression.Lambda(parsedExpression, newParameterExpression) : Expression.Lambda(delegateType, parsedExpression, newParameterExpression); } return delegateType == null ? Expression.Lambda(parsedExpression, parameters) : Expression.Lambda(delegateType, parsedExpression, parameters); } /// <summary> /// Parses an expression into a Typed Expression. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="parsingConfig">The Configuration for the parsing.</param> /// <param name="createParameterCtor">if set to <c>true</c> then also create a constructor for all the parameters. Note that this doesn't work for Linq-to-Database entities.</param> /// <param name="parameters">A array from ParameterExpressions.</param> /// <param name="expression">The expression.</param> /// <param name="values">An object array that contains zero or more objects which are used as replacement values.</param> /// <returns>The generated <see cref="Expression"/></returns> [PublicAPI] public static Expression<Func<TResult>> ParseLambda<TResult>(ParsingConfig? parsingConfig, bool createParameterCtor, ParameterExpression[] parameters, string expression, params object?[] values) { return (Expression<Func<TResult>>)ParseLambda(parsingConfig, createParameterCtor, parameters, typeof(TResult), expression, values); } /// <summary> /// Parses an expression into a Typed Expression. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="delegateType">The delegate type.</param> /// <param name="parsingConfig">The Configuration for the parsing.</param> /// <param name="createParameterCtor">if set to <c>true</c> then also create a constructor for all the parameters. Note that this doesn't work for Linq-to-Database entities.</param> /// <param name="parameters">A array from ParameterExpressions.</param> /// <param name="expression">The expression.</param> /// <param name="values">An object array that contains zero or more objects which are used as replacement values.</param> /// <returns>The generated <see cref="Expression"/></returns> [PublicAPI] public static Expression<Func<TResult>> ParseLambda<TResult>(Type delegateType, ParsingConfig? parsingConfig, bool createParameterCtor, ParameterExpression[] parameters, string expression, params object?[] values) { Check.NotNull(delegateType); return (Expression<Func<TResult>>)ParseLambda(delegateType, parsingConfig, createParameterCtor, parameters, typeof(TResult), expression, values); } /// <summary> /// Parses an expression into a LambdaExpression. /// </summary> /// <param name="createParameterCtor">if set to <c>true</c> then also create a constructor for all the parameters. Note that this doesn't work for Linq-to-Database entities.</param> /// <param name="itType">The main type from the dynamic class expression.</param> /// <param name="resultType">Type of the result. If not specified, it will be generated dynamically.</param> /// <param name="expression">The expression.</param> /// <param name="values">An object array that contains zero or more objects which are used as replacement values.</param> /// <returns>The generated <see cref="LambdaExpression"/></returns> [PublicAPI] public static LambdaExpression ParseLambda(bool createParameterCtor, Type itType, Type? resultType, string expression, params object?[] values) { Check.NotNull(itType); Check.NotEmpty(expression); return ParseLambda(createParameterCtor, new[] { ParameterExpressionHelper.CreateParameterExpression(itType, string.Empty) }, resultType, expression, values); } /// <summary> /// Parses an expression into a Typed Expression. /// </summary> /// <typeparam name="T">The `it`-Type.</typeparam> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="parsingConfig">The Configuration for the parsing.</param> /// <param name="createParameterCtor">if set to <c>true</c> then also create a constructor for all the parameters. Note that this doesn't work for Linq-to-Database entities.</param> /// <param name="expression">The expression.</param> /// <param name="values">An object array that contains zero or more objects which are used as replacement values.</param> /// <returns>The generated <see cref="Expression"/></returns> [PublicAPI] public static Expression<Func<T, TResult>> ParseLambda<T, TResult>(ParsingConfig? parsingConfig, bool createParameterCtor, string expression, params object?[] values) { Check.NotEmpty(expression); return (Expression<Func<T, TResult>>)ParseLambda(parsingConfig, createParameterCtor, new[] { ParameterExpressionHelper.CreateParameterExpression(typeof(T), string.Empty, parsingConfig?.RenameEmptyParameterExpressionNames ?? false) }, typeof(TResult), expression, values); } /// <summary> /// Parses an expression into a Typed Expression. /// </summary> /// <typeparam name="T">The `it`-Type.</typeparam> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="delegateType">The delegate type.</param> /// <param name="parsingConfig">The Configuration for the parsing.</param> /// <param name="createParameterCtor">if set to <c>true</c> then also create a constructor for all the parameters. Note that this doesn't work for Linq-to-Database entities.</param> /// <param name="expression">The expression.</param> /// <param name="values">An object array that contains zero or more objects which are used as replacement values.</param> /// <returns>The generated <see cref="Expression"/></returns> [PublicAPI] public static Expression<Func<T, TResult>> ParseLambda<T, TResult>(Type delegateType, ParsingConfig? parsingConfig, bool createParameterCtor, string expression, params object?[] values) { Check.NotNull(delegateType); Check.NotEmpty(expression); return (Expression<Func<T, TResult>>)ParseLambda(delegateType, parsingConfig, createParameterCtor, new[] { ParameterExpressionHelper.CreateParameterExpression(typeof(T), string.Empty, parsingConfig?.RenameEmptyParameterExpressionNames ?? false) }, typeof(TResult), expression, values); } /// <summary> /// Parses an expression into a LambdaExpression. (Also create a constructor for all the parameters. Note that this doesn't work for Linq-to-Database entities.) /// </summary> /// <param name="parsingConfig">The Configuration for the parsing.</param> /// <param name="resultType">Type of the result. If not specified, it will be generated dynamically.</param> /// <param name="expression">The expression.</param> /// <param name="values">An object array that contains zero or more objects which are used as replacement values.</param> /// <returns>The generated <see cref="LambdaExpression"/></returns> [PublicAPI] public static LambdaExpression ParseLambda(ParsingConfig? parsingConfig, Type? resultType, string expression, params object?[] values) { return ParseLambda(parsingConfig, true, resultType, expression, values); } /// <summary> /// Parses an expression into a LambdaExpression. (Also create a constructor for all the parameters. Note that this doesn't work for Linq-to-Database entities.) /// </summary> /// <param name="delegateType">The delegate type.</param> /// <param name="parsingConfig">The Configuration for the parsing.</param> /// <param name="resultType">Type of the result. If not specified, it will be generated dynamically.</param> /// <param name="expression">The expression.</param> /// <param name="values">An object array that contains zero or more objects which are used as replacement values.</param> /// <returns>The generated <see cref="LambdaExpression"/></returns> [PublicAPI] public static LambdaExpression ParseLambda(Type delegateType, ParsingConfig? parsingConfig, Type? resultType, string expression, params object?[] values) { Check.NotNull(delegateType); return ParseLambda(delegateType, parsingConfig, true, resultType, expression, values); } /// <summary> /// Parses an expression into a LambdaExpression. (Also create a constructor for all the parameters. Note that this doesn't work for Linq-to-Database entities.) /// </summary> /// <param name="resultType">Type of the result. If not specified, it will be generated dynamically.</param> /// <param name="expression">The expression.</param> /// <param name="values">An object array that contains zero or more objects which are used as replacement values.</param> /// <returns>The generated <see cref="LambdaExpression"/></returns> [PublicAPI] public static LambdaExpression ParseLambda(Type? resultType, string expression, params object?[] values) { Check.NotEmpty(expression); return ParseLambda(null, true, resultType, expression, values); } // DO NOT ADD: It create ambiguous method error //[PublicAPI] //public static LambdaExpression ParseLambda([CanBeNull] Type delegateType, [CanBeNull] Type resultType, [NotNull] string expression, params object?[]values) //{ // Check.NotEmpty(expression); // return ParseLambda(delegateType, null, true, resultType, expression, values); //} /// <summary> /// Parses an expression into a LambdaExpression. (Also create a constructor for all the parameters. Note that this doesn't work for Linq-to-Database entities.) /// </summary> /// <param name="itType">The main type from the dynamic class expression.</param> /// <param name="resultType">Type of the result. If not specified, it will be generated dynamically.</param> /// <param name="expression">The expression.</param> /// <param name="values">An object array that contains zero or more objects which are used as replacement values.</param> /// <returns>The generated <see cref="LambdaExpression"/></returns> [PublicAPI] public static LambdaExpression ParseLambda(Type itType, Type? resultType, string expression, params object?[] values) { Check.NotNull(itType); return ParseLambda(true, itType, resultType, expression, values); } /// <summary> /// Parses an expression into a LambdaExpression. (Also create a constructor for all the parameters. Note that this doesn't work for Linq-to-Database entities.) /// </summary> /// <param name="parsingConfig">The Configuration for the parsing.</param> /// <param name="itType">The main type from the dynamic class expression.</param> /// <param name="resultType">Type of the result. If not specified, it will be generated dynamically.</param> /// <param name="expression">The expression.</param> /// <param name="values">An object array that contains zero or more objects which are used as replacement values.</param> /// <returns>The generated <see cref="LambdaExpression"/></returns> [PublicAPI] public static LambdaExpression ParseLambda(ParsingConfig? parsingConfig, Type itType, Type? resultType, string expression, params object?[] values) { Check.NotNull(itType); return ParseLambda(parsingConfig, true, itType, resultType, expression, values); } /// <summary> /// Parses an expression into a LambdaExpression. (Also create a constructor for all the parameters. Note that this doesn't work for Linq-to-Database entities.) /// </summary> /// <param name="delegateType">The delegate type.</param> /// <param name="parsingConfig">The Configuration for the parsing.</param> /// <param name="itType">The main type from the dynamic class expression.</param> /// <param name="resultType">Type of the result. If not specified, it will be generated dynamically.</param> /// <param name="expression">The expression.</param> /// <param name="values">An object array that contains zero or more objects which are used as replacement values.</param> /// <returns>The generated <see cref="LambdaExpression"/></returns> [PublicAPI] public static LambdaExpression ParseLambda(Type delegateType, ParsingConfig? parsingConfig, Type itType, Type? resultType, string expression, params object?[] values) { Check.NotNull(delegateType); Check.NotNull(itType); return ParseLambda(delegateType, parsingConfig, true, itType, resultType, expression, values); } /// <summary> /// Parses an expression into a LambdaExpression. /// </summary> /// <param name="parsingConfig">The Configuration for the parsing.</param> /// <param name="createParameterCtor">if set to <c>true</c> then also create a constructor for all the parameters. Note that this doesn't work for Linq-to-Database entities.</param> /// <param name="itType">The main type from the dynamic class expression.</param> /// <param name="resultType">Type of the result. If not specified, it will be generated dynamically.</param> /// <param name="expression">The expression.</param> /// <param name="values">An object array that contains zero or more objects which are used as replacement values.</param> /// <returns>The generated <see cref="LambdaExpression"/></returns> [PublicAPI] public static LambdaExpression ParseLambda(ParsingConfig? parsingConfig, bool createParameterCtor, Type itType, Type? resultType, string expression, params object?[]? values) { Check.NotNull(itType); Check.NotEmpty(expression); return ParseLambda(parsingConfig, createParameterCtor, new[] { ParameterExpressionHelper.CreateParameterExpression(itType, string.Empty, parsingConfig?.RenameEmptyParameterExpressionNames ?? false) }, resultType, expression, values); } /// <summary> /// Parses an expression into a LambdaExpression. /// </summary> /// <param name="delegateType">The delegate type.</param> /// <param name="parsingConfig">The Configuration for the parsing.</param> /// <param name="createParameterCtor">if set to <c>true</c> then also create a constructor for all the parameters. Note that this doesn't work for Linq-to-Database entities.</param> /// <param name="itType">The main type from the dynamic class expression.</param> /// <param name="resultType">Type of the result. If not specified, it will be generated dynamically.</param> /// <param name="expression">The expression.</param> /// <param name="values">An object array that contains zero or more objects which are used as replacement values.</param> /// <returns>The generated <see cref="LambdaExpression"/></returns> [PublicAPI] public static LambdaExpression ParseLambda(Type delegateType, ParsingConfig? parsingConfig, bool createParameterCtor, Type itType, Type? resultType, string expression, params object?[] values) { Check.NotNull(delegateType); Check.NotNull(itType); Check.NotEmpty(expression); return ParseLambda(delegateType, parsingConfig, createParameterCtor, new[] { ParameterExpressionHelper.CreateParameterExpression(itType, string.Empty, parsingConfig?.RenameEmptyParameterExpressionNames ?? false) }, resultType, expression, values); } /// <summary> /// Parses an expression into a LambdaExpression. (Also create a constructor for all the parameters. Note that this doesn't work for Linq-to-Database entities.) /// </summary> /// <param name="parameters">A array from ParameterExpressions.</param> /// <param name="resultType">Type of the result. If not specified, it will be generated dynamically.</param> /// <param name="expression">The expression.</param> /// <param name="values">An object array that contains zero or more objects which are used as replacement values.</param> /// <returns>The generated <see cref="LambdaExpression"/></returns> [PublicAPI] public static LambdaExpression ParseLambda(ParameterExpression[] parameters, Type? resultType, string expression, params object?[] values) { return ParseLambda(null, true, parameters, resultType, expression, values); } /// <summary> /// Parses an expression into a LambdaExpression. (Also create a constructor for all the parameters. Note that this doesn't work for Linq-to-Database entities.) /// </summary> /// <param name="delegateType">The delegate type.</param> /// <param name="parameters">A array from ParameterExpressions.</param> /// <param name="resultType">Type of the result. If not specified, it will be generated dynamically.</param> /// <param name="expression">The expression.</param> /// <param name="values">An object array that contains zero or more objects which are used as replacement values.</param> /// <returns>The generated <see cref="LambdaExpression"/></returns> [PublicAPI] public static LambdaExpression ParseLambda(Type delegateType, ParameterExpression[] parameters, Type? resultType, string expression, params object?[] values) { Check.NotNull(delegateType); return ParseLambda(delegateType, null, true, parameters, resultType, expression, values); } /// <summary> /// Parses an expression into a LambdaExpression. (Also create a constructor for all the parameters. Note that this doesn't work for Linq-to-Database entities.) /// </summary> /// <param name="parsingConfig">The Configuration for the parsing.</param> /// <param name="parameters">A array from ParameterExpressions.</param> /// <param name="resultType">Type of the result. If not specified, it will be generated dynamically.</param> /// <param name="expression">The expression.</param> /// <param name="values">An object array that contains zero or more objects which are used as replacement values.</param> /// <returns>The generated <see cref="LambdaExpression"/></returns> [PublicAPI] public static LambdaExpression ParseLambda(ParsingConfig? parsingConfig, ParameterExpression[] parameters, Type? resultType, string expression, params object?[] values) { return ParseLambda(parsingConfig, true, parameters, resultType, expression, values); } /// <summary> /// Parses an expression into a LambdaExpression. (Also create a constructor for all the parameters. Note that this doesn't work for Linq-to-Database entities.) /// </summary> /// <param name="delegateType">The delegate type.</param> /// <param name="parsingConfig">The Configuration for the parsing.</param> /// <param name="parameters">A array from ParameterExpressions.</param> /// <param name="resultType">Type of the result. If not specified, it will be generated dynamically.</param> /// <param name="expression">The expression.</param> /// <param name="values">An object array that contains zero or more objects which are used as replacement values.</param> /// <returns>The generated <see cref="LambdaExpression"/></returns> [PublicAPI] public static LambdaExpression ParseLambda(Type delegateType, ParsingConfig? parsingConfig, ParameterExpression[] parameters, Type? resultType, string expression, params object?[] values) { Check.NotNull(delegateType); return ParseLambda(delegateType, parsingConfig, true, parameters, resultType, expression, values); } /// <summary> /// Parses an expression into a LambdaExpression. /// </summary> /// <param name="createParameterCtor">if set to <c>true</c> then also create a constructor for all the parameters. Note that this doesn't work for Linq-to-Database entities.</param> /// <param name="parameters">A array from ParameterExpressions.</param> /// <param name="resultType">Type of the result. If not specified, it will be generated dynamically.</param> /// <param name="expression">The expression.</param> /// <param name="values">An object array that contains zero or more objects which are used as replacement values.</param> /// <returns>The generated <see cref="LambdaExpression"/></returns> [PublicAPI] public static LambdaExpression ParseLambda(bool createParameterCtor, ParameterExpression[] parameters, Type? resultType, string expression, params object?[] values) { return ParseLambda(null, createParameterCtor, parameters, resultType, expression, values); } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/DynamicExpressionParser.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
6,151
```smalltalk #if !(NET35 || NET40) using System.Collections; using System.Collections.Generic; using System.Linq.Dynamic.Core.Validation; using System.Reflection; using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; namespace System.Linq.Dynamic.Core; /// <summary> /// Define async extensions on <see cref="IEnumerable"/>. /// </summary> public static class DynamicEnumerableAsyncExtensions { private static readonly MethodInfo ToListAsyncGenericMethod; static DynamicEnumerableAsyncExtensions() { ToListAsyncGenericMethod = typeof(DynamicEnumerableAsyncExtensions).GetTypeInfo() .GetDeclaredMethods("ToListAsync") .First(x => x.IsGenericMethod); } /// <summary> /// Async creates an array of dynamic objects from a <see cref="IEnumerable"/>. /// </summary> /// <param name="source">A <see cref="IEnumerable"/> to create an array from.</param> /// <param name="type">A <see cref="Type"/> cast to.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> (optional).</param> /// <returns>An Array that contains the elements from the input sequence.</returns> [PublicAPI] public static async Task<dynamic[]> ToDynamicArrayAsync(this IEnumerable source, Type type, CancellationToken cancellationToken = default) { var result = await ToDynamicListAsync(Check.NotNull(source), Check.NotNull(type), cancellationToken).ConfigureAwait(false); return result.ToArray(); } /// <summary> /// Async creates an array of dynamic objects from a <see cref="IEnumerable"/>. /// </summary> /// <param name="source">A <see cref="IEnumerable"/> to create an array from.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> (optional).</param> /// <returns>An array that contains the elements from the input sequence.</returns> [PublicAPI] public static async Task<dynamic[]> ToDynamicArrayAsync(this IEnumerable source, CancellationToken cancellationToken = default) { return (await ToListAsync<dynamic>(Check.NotNull(source), cancellationToken).ConfigureAwait(false)).ToArray(); } /// <summary> /// Async creates an array of dynamic objects from a <see cref="IEnumerable"/>. /// </summary> /// <typeparam name="T">The generic type.</typeparam> /// <param name="source">A <see cref="IEnumerable"/> to create an array from.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> (optional).</param> /// <returns>An Array{T} that contains the elements from the input sequence.</returns> [PublicAPI] public static async Task<T[]> ToDynamicArrayAsync<T>(this IEnumerable source, CancellationToken cancellationToken = default) { return (await ToListAsync<T>(Check.NotNull(source), cancellationToken).ConfigureAwait(false)).ToArray(); } /// <summary> /// Async creates a list of dynamic objects from a <see cref="IEnumerable"/>. /// </summary> /// <param name="source">A <see cref="IEnumerable"/> to create an array from.</param> /// <param name="type">A <see cref="Type"/> cast to.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> (optional).</param> /// <returns>An List that contains the elements from the input sequence.</returns> [PublicAPI] public static async Task<List<dynamic>> ToDynamicListAsync(this IEnumerable source, Type type, CancellationToken cancellationToken = default) { Check.NotNull(source); Check.NotNull(type); var task = (Task)ToListAsyncGenericMethod.MakeGenericMethod(type).Invoke(source, new object[] { source, cancellationToken })!; await task.ConfigureAwait(false); var list = (IList)task.GetType().GetProperty(nameof(Task<object>.Result))!.GetValue(task)!; return list.Cast<dynamic>().ToList(); } /// <summary> /// Async creates a list of dynamic objects from a <see cref="IEnumerable"/>. /// </summary> /// <param name="source">A <see cref="IEnumerable"/> to create a list from.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> (optional).</param> /// <returns>A List that contains the elements from the input sequence.</returns> [PublicAPI] public static Task<List<dynamic>> ToDynamicListAsync(this IEnumerable source, CancellationToken cancellationToken = default) { return ToListAsync<dynamic>(Check.NotNull(source), cancellationToken); } /// <summary> /// Async creates a list of dynamic objects from an <see cref="IEnumerable"/>. /// </summary> /// <typeparam name="T">Generic Type</typeparam> /// <param name="source">A <see cref="IEnumerable"/> to create a list from.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> (optional).</param> /// <returns>A List{T} that contains the elements from the input sequence.</returns> [PublicAPI] public static Task<List<T>> ToDynamicListAsync<T>(this IEnumerable source, CancellationToken cancellationToken = default) { return ToListAsync<T>(Check.NotNull(source), cancellationToken); } #pragma warning disable CS1998 // ReSharper disable once UnusedParameter.Local private static async Task<List<T>> ToListAsync<T>(IEnumerable source, CancellationToken cancellationToken) #pragma warning restore CS1998 { switch (source) { #if NETSTANDARD2_1_OR_GREATER || ASYNCENUMERABLE case IAsyncEnumerable<T> asyncEnumerable: var list = new List<T>(); await foreach (var element in asyncEnumerable.WithCancellation(cancellationToken).ConfigureAwait(false)) { list.Add(element); } return list; #endif case IEnumerable<T> enumerable: return enumerable.ToList(); default: return source.Cast<T>().ToList(); } } } #endif ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/DynamicEnumerableAsyncExtensions.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
1,234
```smalltalk #if !UAP10_0 using System.Reflection; using System.Reflection.Emit; namespace System.Linq.Dynamic.Core { internal static class AssemblyBuilderFactory { /// <summary> /// Defines a dynamic assembly that has the specified name and access rights. /// </summary> /// <param name="name">The name of the assembly.</param> /// <param name="access">The access rights of the assembly.</param> /// <returns>An object that represents the new assembly.</returns> public static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access) { #if (NET35 || NET40 || SILVERLIGHT) return AppDomain.CurrentDomain.DefineDynamicAssembly(name, access); #else return AssemblyBuilder.DefineDynamicAssembly(name, access); #endif } } } #endif ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/AssemblyBuilderFactory.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
174
```smalltalk #if !NET35 && !UAP10_0 && !NETSTANDARD1_3 using System.Collections; using System.Collections.Generic; using System.Dynamic; using System.Linq.Expressions; using System.Reflection; namespace System.Linq.Dynamic.Core; /// <summary> /// </summary> /// <seealso cref="GetMemberBinder" /> internal class DynamicGetMemberBinder : GetMemberBinder { private static readonly MethodInfo DynamicGetMemberMethod = typeof(DynamicGetMemberBinder).GetMethod(nameof(GetDynamicMember))!; public DynamicGetMemberBinder(string name, ParsingConfig? config) : base(name, config?.IsCaseSensitive != true) { } public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject? errorSuggestion) { var instance = Expression.Call( DynamicGetMemberMethod, target.Expression, Expression.Constant(Name), Expression.Constant(IgnoreCase)); return DynamicMetaObject.Create(target.Value!, instance); } public static object? GetDynamicMember(object value, string name, bool ignoreCase) { if (value == null) { throw new InvalidOperationException(); } if (value is IDictionary<string, object> stringObjectDictionary) { return stringObjectDictionary[name]; } if (value is IDictionary nonGenericDictionary) { return nonGenericDictionary[name]; } var flags = BindingFlags.Instance | BindingFlags.Public; if (ignoreCase) { flags |= BindingFlags.IgnoreCase; } var type = value.GetType(); var property = type.GetProperty(name, flags); if (property == null) { throw new InvalidOperationException($"Unable to find property '{name}' on type '{type}'."); } return property.GetValue(value, null); } } #endif ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/DynamicGetMemberBinder.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
369
```smalltalk using System.ComponentModel; using System.Linq.Dynamic.Core.Parser; using System.Linq.Dynamic.Core.Validation; namespace System.Linq.Dynamic.Core.TypeConverters; internal class TypeConverterFactory : ITypeConverterFactory { private readonly ParsingConfig _config; #if NET6_0 static TypeConverterFactory() { TypeDescriptor.AddAttributes(typeof(DateOnly), new TypeConverterAttribute(typeof(DateOnlyConverter))); TypeDescriptor.AddAttributes(typeof(TimeOnly), new TypeConverterAttribute(typeof(TimeOnlyConverter))); } #endif public TypeConverterFactory(ParsingConfig config) { _config = Check.NotNull(config); } /// <see cref="ITypeConverterFactory.GetConverter"/> public TypeConverter GetConverter(Type type) { Check.NotNull(type); if (_config.DateTimeIsParsedAsUTC && (type == typeof(DateTime) || type == typeof(DateTime?))) { return new CustomDateTimeConverter(); } var typeToCheck = TypeHelper.IsNullableType(type) ? TypeHelper.GetNonNullableType(type) : type; if (_config.TypeConverters != null && _config.TypeConverters.TryGetValue(typeToCheck, out var typeConverter)) { return typeConverter; } #if !SILVERLIGHT return TypeDescriptor.GetConverter(type); #else var attributes = type.GetCustomAttributes(typeof(TypeConverterAttribute), false); if (attributes.Length != 1) return new TypeConverter(); var converterAttribute = (TypeConverterAttribute)attributes[0]; var converterType = Type.GetType(converterAttribute.ConverterTypeName); if (converterType == null) return new TypeConverter(); return (TypeConverter) Activator.CreateInstance(converterType); #endif } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/TypeConverters/TypeConverterFactory.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
347
```smalltalk #if NET6_0 using System.ComponentModel; using System.Globalization; namespace System.Linq.Dynamic.Core.TypeConverters; /// <summary> /// Based on path_to_url /// </summary> internal class DateOnlyConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) { return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); } public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destinationType) { return destinationType == typeof(string) || base.CanConvertTo(context, destinationType); } public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value) { if (value is string s) { return DateOnly.Parse(s, culture); } return base.ConvertFrom(context, culture, value); } public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { if (destinationType == typeof(string)) { return ((DateOnly?)value)?.ToString(culture); } return base.ConvertTo(context, culture, value, destinationType); } public override bool IsValid(ITypeDescriptorContext? context, object? value) { return value is DateOnly || base.IsValid(context, value); } } #endif ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/TypeConverters/DateOnlyConverter.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
291
```smalltalk using System.Collections.Generic; using System.Collections; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq.Dynamic.Core.Exceptions; using System.Linq.Dynamic.Core.Validation; using System.Linq.Expressions; using System.Reflection; using JetBrains.Annotations; using System.Linq.Dynamic.Core.Parser; using System.Linq.Dynamic.Core.Util; #if !(SILVERLIGHT) using System.Diagnostics; #endif namespace System.Linq.Dynamic.Core { /// <summary> /// Provides a set of static (Shared in Visual Basic) methods for querying data structures that implement <see cref="IQueryable"/>. /// It allows dynamic string based querying. Very handy when, at compile time, you don't know the type of queries that will be generated, /// or when downstream components only return column names to sort and filter by. /// </summary> [SuppressMessage("ReSharper", "PossibleMultipleEnumeration")] public static class DynamicQueryableExtensions { #if !(SILVERLIGHT) private static readonly TraceSource TraceSource = new(nameof(DynamicQueryableExtensions)); #endif private static Expression OptimizeExpression(Expression expression) { if (ExtensibilityPoint.QueryOptimizer != null) { var optimized = ExtensibilityPoint.QueryOptimizer(expression); #if !(SILVERLIGHT) if (optimized != expression) { TraceSource.TraceEvent(TraceEventType.Verbose, 0, "Expression before : {0}", expression); TraceSource.TraceEvent(TraceEventType.Verbose, 0, "Expression after : {0}", optimized); } #endif return optimized; } return expression; } #region Aggregate /// <summary> /// Dynamically runs an aggregate function on the IQueryable. /// </summary> /// <param name="source">The IQueryable data source.</param> /// <param name="function">The name of the function to run. Can be Sum, Average, Min or Max.</param> /// <param name="member">The name of the property to aggregate over.</param> /// <returns>The value of the aggregate function run over the specified property.</returns> public static object Aggregate(this IQueryable source, string function, string member) { Check.NotNull(source); Check.NotEmpty(function); Check.NotEmpty(member); // Properties PropertyInfo property = source.ElementType.GetProperty(member)!; ParameterExpression parameter = ParameterExpressionHelper.CreateParameterExpression(source.ElementType, "s"); Expression selector = Expression.Lambda(Expression.MakeMemberAccess(parameter, property), parameter); // We've tried to find an expression of the type Expression<Func<TSource, TAcc>>, // which is expressed as ( (TSource s) => s.Price ); var methods = typeof(Queryable).GetMethods().Where(x => x.Name == function && x.IsGenericMethod).ToArray(); // Method MethodInfo? aggregateMethod = methods.SingleOrDefault(m => { var lastParameter = m.GetParameters().LastOrDefault(); return lastParameter != null && TypeHelper.GetUnderlyingType(lastParameter.ParameterType) == property.PropertyType; }); // Sum, Average if (aggregateMethod != null) { return source.Provider.Execute( Expression.Call( null, aggregateMethod.MakeGenericMethod(source.ElementType), new[] { source.Expression, Expression.Quote(selector) }))!; } // Min, Max aggregateMethod = methods.SingleOrDefault(m => m.Name == function && m.GetGenericArguments().Length == 2); return source.Provider.Execute( Expression.Call( null, aggregateMethod!.MakeGenericMethod(source.ElementType, property.PropertyType), new[] { source.Expression, Expression.Quote(selector) }))!; } #endregion Aggregate #region All private static readonly MethodInfo _AllPredicate = QueryableMethodFinder.GetMethod(nameof(Queryable.All), 1); /// <summary>Determines whether all the elements of a sequence satisfy a condition.</summary> /// <param name="source">A sequence whose elements to test for a condition.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>true if every element of the source sequence passes the test in the specified predicate, or if the sequence is empty; otherwise, false.</returns> [PublicAPI] public static bool All(this IQueryable source, string predicate, params object?[] args) { return All(source, ParsingConfig.Default, predicate, args); } /// <summary>Determines whether all the elements of a sequence satisfy a condition.</summary> /// <param name="source">A sequence whose elements to test for a condition.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>true if every element of the source sequence passes the test in the specified predicate, or if the sequence is empty; otherwise, false.</returns> [PublicAPI] public static bool All(this IQueryable source, ParsingConfig config, string predicate, params object?[] args) { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(predicate); bool createParameterCtor = SupportsLinqToObjects(config, source); LambdaExpression lambda = DynamicExpressionParser.ParseLambda(createParameterCtor, source.ElementType, null, predicate, args); return Execute<bool>(_AllPredicate, source, Expression.Quote(lambda)); } #endregion All #region Any private static readonly MethodInfo _any = QueryableMethodFinder.GetMethod(nameof(Queryable.Any)); /// <summary> /// Determines whether a sequence contains any elements. /// </summary> /// <param name="source">A sequence to check for being empty.</param> /// <example> /// <code language="cs"> /// IQueryable queryable = employees.AsQueryable(); /// var result = queryable.Any(); /// </code> /// </example> /// <returns>true if the source sequence contains any elements; otherwise, false.</returns> public static bool Any(this IQueryable source) { return Execute<bool>(_any, Check.NotNull(source)); } private static readonly MethodInfo _anyPredicate = QueryableMethodFinder.GetMethod(nameof(Queryable.Any), 1); /// <summary> /// Determines whether a sequence contains any elements. /// </summary> /// <param name="source">A sequence to check for being empty.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <example> /// <code language="cs"> /// IQueryable queryable = employees.AsQueryable(); /// var result1 = queryable.Any("Income > 50"); /// var result2 = queryable.Any("Income > @0", 50); /// var result3 = queryable.Select("Roles.Any()"); /// </code> /// </example> /// <returns>true if the source sequence contains any elements; otherwise, false.</returns> [PublicAPI] public static bool Any(this IQueryable source, ParsingConfig config, string predicate, params object?[] args) { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(predicate); bool createParameterCtor = SupportsLinqToObjects(config, source); LambdaExpression lambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args); return Execute<bool>(_anyPredicate, source, lambda); } /// <inheritdoc cref="Any(IQueryable, ParsingConfig, string, object[])"/> public static bool Any(this IQueryable source, string predicate, params object?[] args) { return Any(source, ParsingConfig.Default, predicate, args); } /// <summary> /// Determines whether a sequence contains any elements. /// </summary> /// <param name="source">A sequence to check for being empty.</param> /// <param name="lambda">A cached Lambda Expression.</param> /// <returns>true if the source sequence contains any elements; otherwise, false.</returns> public static bool Any(this IQueryable source, LambdaExpression lambda) { Check.NotNull(source); Check.NotNull(lambda); return Execute<bool>(_anyPredicate, source, lambda); } #endregion Any #region Average /// <summary> /// Computes the average of a sequence of numeric values. /// </summary> /// <param name="source">A sequence of numeric values to calculate the average of.</param> /// <example> /// <code language="cs"> /// IQueryable queryable = employees.AsQueryable(); /// var result1 = queryable.Average(); /// var result2 = queryable.Select("Roles.Average()"); /// </code> /// </example> /// <returns>The average of the values in the sequence.</returns> [PublicAPI] public static double Average(this IQueryable source) { Check.NotNull(source); var average = QueryableMethodFinder.GetMethod(nameof(Queryable.Average), source.ElementType, typeof(double)); return Execute<double>(average, source); } /// <summary> /// Computes the average of a sequence of numeric values. /// </summary> /// <param name="source">A sequence of numeric values to calculate the average of.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <example> /// <code language="cs"> /// IQueryable queryable = employees.AsQueryable(); /// var result = queryable.Average("Income"); /// </code> /// </example> /// <returns>The average of the values in the sequence.</returns> [PublicAPI] public static double Average(this IQueryable source, ParsingConfig config, string predicate, params object?[] args) { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(predicate); bool createParameterCtor = SupportsLinqToObjects(config, source); LambdaExpression lambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args); return Average(source, lambda); } /// <inheritdoc cref="Average(IQueryable, ParsingConfig, string, object[])"/> [PublicAPI] public static double Average(this IQueryable source, string predicate, params object?[] args) { return Average(source, ParsingConfig.Default, predicate, args); } /// <summary> /// Computes the average of a sequence of numeric values. /// </summary> /// <param name="source">A sequence of numeric values to calculate the average of.</param> /// <param name="lambda">A Lambda Expression.</param> /// <returns>The average of the values in the sequence.</returns> [PublicAPI] public static double Average(this IQueryable source, LambdaExpression lambda) { Check.NotNull(source); Check.NotNull(lambda); var averageSelector = QueryableMethodFinder.GetMethod(nameof(Queryable.Average), lambda.GetReturnType(), typeof(double), 1); return Execute<double>(averageSelector, source, lambda); } #endregion Average #region AsDynamicEnumerable #if NET35 /// <summary> /// Returns the input typed as <see cref="IEnumerable{T}"/> of <see cref="object"/>./> /// </summary> /// <param name="source">The sequence to type as <see cref="IEnumerable{T}"/> of <see cref="object"/>.</param> /// <returns>The input typed as <see cref="IEnumerable{T}"/> of <see cref="object"/>.</returns> public static IEnumerable<object> AsDynamicEnumerable(this IQueryable source) #else /// <summary> /// Returns the input typed as <see cref="IEnumerable{T}"/> of dynamic. /// </summary> /// <param name="source">The sequence to type as <see cref="IEnumerable{T}"/> of dynamic.</param> /// <returns>The input typed as <see cref="IEnumerable{T}"/> of dynamic.</returns> public static IEnumerable<dynamic> AsDynamicEnumerable(this IQueryable source) #endif { foreach (var obj in source) { yield return obj; } } #endregion AsDynamicEnumerable #region Cast private static readonly MethodInfo _cast = QueryableMethodFinder.GetGenericMethod(nameof(Queryable.Cast)); /// <summary> /// Converts the elements of an <see cref="IQueryable"/> to the specified type. /// </summary> /// <param name="source">The <see cref="IQueryable"/> that contains the elements to be converted.</param> /// <param name="type">The type to convert the elements of source to.</param> /// <returns>An <see cref="IQueryable"/> that contains each element of the source sequence converted to the specified type.</returns> public static IQueryable Cast(this IQueryable source, Type type) { Check.NotNull(source); Check.NotNull(type); var optimized = OptimizeExpression(Expression.Call(null, _cast.MakeGenericMethod(new[] { type }), new[] { source.Expression })); return source.Provider.CreateQuery(optimized); } /// <summary> /// Converts the elements of an <see cref="IQueryable"/> to the specified type. /// </summary> /// <param name="source">The <see cref="IQueryable"/> that contains the elements to be converted.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="typeName">The type to convert the elements of source to.</param> /// <returns>An <see cref="IQueryable"/> that contains each element of the source sequence converted to the specified type.</returns> public static IQueryable Cast(this IQueryable source, ParsingConfig config, string typeName) { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(typeName, nameof(typeName)); var finder = new TypeFinder(config, new KeywordsHelper(config)); Type type = finder.FindTypeByName(typeName, null, true)!; return Cast(source, type); } /// <summary> /// Converts the elements of an <see cref="IQueryable"/> to the specified type. /// </summary> /// <param name="source">The <see cref="IQueryable"/> that contains the elements to be converted.</param> /// <param name="typeName">The type to convert the elements of source to.</param> /// <returns>An <see cref="IQueryable"/> that contains each element of the source sequence converted to the specified type.</returns> public static IQueryable Cast(this IQueryable source, string typeName) { return Cast(source, ParsingConfig.Default, typeName); } #endregion Cast #region Count private static readonly MethodInfo _count = QueryableMethodFinder.GetMethod(nameof(Queryable.Count)); /// <summary> /// Returns the number of elements in a sequence. /// </summary> /// <param name="source">The <see cref="IQueryable"/> that contains the elements to be counted.</param> /// <example> /// <code language="cs"> /// IQueryable queryable = employees.AsQueryable(); /// var result = queryable.Count(); /// </code> /// </example> /// <returns>The number of elements in the input sequence.</returns> public static int Count(this IQueryable source) { Check.NotNull(source); return Execute<int>(_count, source); } private static readonly MethodInfo _countPredicate = QueryableMethodFinder.GetMethod(nameof(Queryable.Count), 1); /// <summary> /// Returns the number of elements in a sequence. /// </summary> /// <param name="source">The <see cref="IQueryable"/> that contains the elements to be counted.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <example> /// <code language="cs"> /// IQueryable queryable = employees.AsQueryable(); /// var result1 = queryable.Count("Income > 50"); /// var result2 = queryable.Count("Income > @0", 50); /// var result3 = queryable.Select("Roles.Count()"); /// </code> /// </example> /// <returns>The number of elements in the specified sequence that satisfies a condition.</returns> [PublicAPI] public static int Count(this IQueryable source, ParsingConfig config, string predicate, params object?[] args) { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(predicate); bool createParameterCtor = SupportsLinqToObjects(config, source); LambdaExpression lambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args); return Execute<int>(_countPredicate, source, lambda); } /// <inheritdoc cref="Count(IQueryable, ParsingConfig, string, object[])"/> public static int Count(this IQueryable source, string predicate, params object?[] args) { return Count(source, ParsingConfig.Default, predicate, args); } /// <summary> /// Returns the number of elements in a sequence. /// </summary> /// <param name="source">The <see cref="IQueryable"/> that contains the elements to be counted.</param> /// <param name="lambda">A cached Lambda Expression.</param> /// <returns>The number of elements in the specified sequence that satisfies a condition.</returns> public static int Count(this IQueryable source, LambdaExpression lambda) { Check.NotNull(source); Check.NotNull(lambda); return Execute<int>(_countPredicate, source, lambda); } #endregion Count #region DefaultIfEmpty private static readonly MethodInfo _defaultIfEmpty = QueryableMethodFinder.GetMethod(nameof(Queryable.DefaultIfEmpty)); private static readonly MethodInfo _defaultIfEmptyWithParam = QueryableMethodFinder.GetMethod(nameof(Queryable.DefaultIfEmpty), 1); /// <summary> /// Returns the elements of the specified sequence or the type parameter's default value in a singleton collection if the sequence is empty. /// </summary> /// <param name="source">The <see cref="IQueryable"/> to return a default value for if empty.</param> /// <example> /// <code language="cs"> /// IQueryable queryable = employees.DefaultIfEmpty(); /// </code> /// </example> /// <returns>An <see cref="IQueryable"/> that contains default if source is empty; otherwise, source.</returns> public static IQueryable DefaultIfEmpty(this IQueryable source) { Check.NotNull(source); return CreateQuery(_defaultIfEmpty, source); } /// <summary> /// Returns the elements of the specified sequence or the type parameter's default value in a singleton collection if the sequence is empty. /// </summary> /// <param name="source">The <see cref="IQueryable"/> to return a default value for if empty.</param> /// <param name="defaultValue">The value to return if the sequence is empty.</param> /// <example> /// <code language="cs"> /// IQueryable queryable = employees.DefaultIfEmpty(new Employee()); /// </code> /// </example> /// <returns>An <see cref="IQueryable"/> that contains defaultValue if source is empty; otherwise, source.</returns> public static IQueryable DefaultIfEmpty(this IQueryable source, object? defaultValue) { Check.NotNull(source); return CreateQuery(_defaultIfEmptyWithParam, source, Expression.Constant(defaultValue)); } #endregion #region Distinct private static readonly MethodInfo _distinct = QueryableMethodFinder.GetMethod(nameof(Queryable.Distinct)); /// <summary> /// Returns distinct elements from a sequence by using the default equality comparer to compare values. /// </summary> /// <param name="source">The sequence to remove duplicate elements from.</param> /// <example> /// <code language="cs"> /// IQueryable queryable = employees.AsQueryable(); /// var result1 = queryable.Distinct(); /// var result2 = queryable.Select("Roles.Distinct()"); /// </code> /// </example> /// <returns>An <see cref="IQueryable"/> that contains distinct elements from the source sequence.</returns> public static IQueryable Distinct(this IQueryable source) { Check.NotNull(source); return CreateQuery(_distinct, source); } #endregion Distinct #region First private static readonly MethodInfo _first = QueryableMethodFinder.GetMethod(nameof(Queryable.First)); /// <summary> /// Returns the first element of a sequence. /// </summary> /// <param name="source">The <see cref="IQueryable"/> to return the first element of.</param> /// <returns>The first element in source.</returns> #if NET35 public static object First(this IQueryable source) #else public static dynamic First(this IQueryable source) #endif { Check.NotNull(source); return Execute(_first, source); } private static readonly MethodInfo _firstPredicate = QueryableMethodFinder.GetMethod(nameof(Queryable.First), 1); /// <summary> /// Returns the first element of a sequence that satisfies a specified condition. /// </summary> /// <param name="source">The <see cref="IQueryable"/> to return the first element of.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>The first element in source that passes the test in predicate.</returns> [PublicAPI] #if NET35 public static object First(this IQueryable source, ParsingConfig config, string predicate, params object?[] args) #else public static dynamic First(this IQueryable source, ParsingConfig config, string predicate, params object?[] args) #endif { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(predicate); bool createParameterCtor = SupportsLinqToObjects(config, source); LambdaExpression lambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args); return Execute(_firstPredicate, source, lambda); } /// <inheritdoc cref="First(IQueryable, ParsingConfig, string, object[])"/> #if NET35 public static object First(this IQueryable source, string predicate, params object?[] args) #else public static dynamic First(this IQueryable source, string predicate, params object?[] args) #endif { return First(source, ParsingConfig.Default, predicate, args); } /// <summary> /// Returns the first element of a sequence that satisfies a specified condition. /// </summary> /// <param name="source">The <see cref="IQueryable"/> to return the first element of.</param> /// <param name="lambda">A cached Lambda Expression.</param> /// <returns>The first element in source that passes the test in predicate.</returns> #if NET35 public static object First(this IQueryable source, LambdaExpression lambda) #else public static dynamic First(this IQueryable source, LambdaExpression lambda) #endif { Check.NotNull(source); return Execute(_firstPredicate, source, lambda); } #endregion First #region FirstOrDefault private static readonly MethodInfo _firstOrDefault = QueryableMethodFinder.GetMethod(nameof(Queryable.FirstOrDefault)); private static readonly MethodInfo _firstOrDefaultPredicate = QueryableMethodFinder.GetMethodWithExpressionParameter(nameof(Queryable.FirstOrDefault)); /// <summary> /// Returns the first element of a sequence, or a default value if the sequence contains no elements. /// </summary> /// <param name="source">The <see cref="IQueryable"/> to return the first element of.</param> /// <returns>default if source is empty; otherwise, the first element in source.</returns> #if NET35 public static object FirstOrDefault(this IQueryable source) #else public static dynamic FirstOrDefault(this IQueryable source) #endif { Check.NotNull(source); return Execute(_firstOrDefault, source); } /// <summary> /// Returns the first element of a sequence that satisfies a specified condition or a default value if no such element is found. /// </summary> /// <param name="source">The <see cref="IQueryable"/> to return the first element of.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>default if source is empty or if no element passes the test specified by predicate; otherwise, the first element in source that passes the test specified by predicate.</returns> [PublicAPI] #if NET35 public static object FirstOrDefault(this IQueryable source, ParsingConfig config, string predicate, params object?[] args) #else public static dynamic FirstOrDefault(this IQueryable source, ParsingConfig config, string predicate, params object?[] args) #endif { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(predicate); bool createParameterCtor = SupportsLinqToObjects(config, source); LambdaExpression lambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args); return Execute(_firstOrDefaultPredicate, source, lambda); } /// <inheritdoc cref="FirstOrDefault(IQueryable, ParsingConfig, string, object[])"/> #if NET35 public static object FirstOrDefault(this IQueryable source, string predicate, params object?[] args) #else public static dynamic FirstOrDefault(this IQueryable source, string predicate, params object?[] args) #endif { return FirstOrDefault(source, ParsingConfig.Default, predicate, args); } /// <summary> /// Returns the first element of a sequence that satisfies a specified condition or a default value if no such element is found. /// </summary> /// <param name="source">The <see cref="IQueryable"/> to return the first element of.</param> /// <param name="lambda">A cached Lambda Expression.</param> /// <returns>default if source is empty or if no element passes the test specified by predicate; otherwise, the first element in source that passes the test specified by predicate.</returns> #if NET35 public static object FirstOrDefault(this IQueryable source, LambdaExpression lambda) #else public static dynamic FirstOrDefault(this IQueryable source, LambdaExpression lambda) #endif { Check.NotNull(source); return Execute(_firstOrDefaultPredicate, source, lambda); } #endregion FirstOrDefault #region GroupBy /// <summary> /// Groups the elements of a sequence according to a specified key string function /// and creates a result value from each group and its key. /// </summary> /// <param name="source">A <see cref="IQueryable"/> whose elements to group.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="keySelector">A string expression to specify the key for each element.</param> /// <param name="resultSelector">A string expression to specify a result value from each group.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>A <see cref="IQueryable"/> where each element represents a projection over a group and its key.</returns> /// <example> /// <code> /// var groupResult1 = queryable.GroupBy("NumberPropertyAsKey", "StringProperty"); /// var groupResult2 = queryable.GroupBy("new (NumberPropertyAsKey, StringPropertyAsKey)", "new (StringProperty1, StringProperty2)"); /// </code> /// </example> [PublicAPI] public static IQueryable GroupBy(this IQueryable source, ParsingConfig config, string keySelector, string resultSelector, object[] args) { return InternalGroupBy(source, config, keySelector, resultSelector, null, args); } /// <summary> /// Groups the elements of a sequence according to a specified key string function /// and creates a result value from each group and its key. /// </summary> /// <param name="source">A <see cref="IQueryable"/> whose elements to group.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="keySelector">A string expression to specify the key for each element.</param> /// <param name="resultSelector">A string expression to specify a result value from each group.</param> /// <param name="equalityComparer">The comparer to use.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>A <see cref="IQueryable"/> where each element represents a projection over a group and its key.</returns> public static IQueryable GroupBy(this IQueryable source, ParsingConfig config, string keySelector, string resultSelector, IEqualityComparer? equalityComparer, object[]? args) { return InternalGroupBy(source, config, keySelector, resultSelector, equalityComparer, args); } internal static IQueryable InternalGroupBy(IQueryable source, ParsingConfig config, string keySelector, string resultSelector, IEqualityComparer? equalityComparer, object[]? args) { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(keySelector, nameof(keySelector)); Check.NotEmpty(resultSelector, nameof(resultSelector)); bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, source); LambdaExpression keyLambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, keySelector, args); LambdaExpression elementLambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, resultSelector, args); Expression? optimized; if (equalityComparer == null) { optimized = OptimizeExpression(Expression.Call( typeof(Queryable), nameof(Queryable.GroupBy), new[] { source.ElementType, keyLambda.Body.Type, elementLambda.Body.Type }, source.Expression, Expression.Quote(keyLambda), Expression.Quote(elementLambda))); } else { var equalityComparerGenericType = typeof(IEqualityComparer<>).MakeGenericType(keyLambda.Body.Type); optimized = OptimizeExpression(Expression.Call( typeof(Queryable), nameof(Queryable.GroupBy), new[] { source.ElementType, keyLambda.Body.Type, elementLambda.Body.Type }, source.Expression, Expression.Quote(keyLambda), Expression.Quote(elementLambda), Expression.Constant(equalityComparer, equalityComparerGenericType))); } return source.Provider.CreateQuery(optimized); } /// <inheritdoc cref="GroupBy(IQueryable, ParsingConfig, string, string, object[])"/> [PublicAPI] public static IQueryable GroupBy(this IQueryable source, string keySelector, string resultSelector, object[] args) { return GroupBy(source, ParsingConfig.Default, keySelector, resultSelector, args); } /// <inheritdoc cref="GroupBy(IQueryable, ParsingConfig, string, string, IEqualityComparer, object[])"/> public static IQueryable GroupBy(this IQueryable source, string keySelector, string resultSelector, IEqualityComparer equalityComparer, object[] args) { return GroupBy(source, ParsingConfig.Default, keySelector, resultSelector, equalityComparer, args); } /// <summary> /// Groups the elements of a sequence according to a specified key string function /// and creates a result value from each group and its key. /// </summary> /// <param name="source">A <see cref="IQueryable"/> whose elements to group.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="keySelector">A string expression to specify the key for each element.</param> /// <param name="resultSelector">A string expression to specify a result value from each group.</param> /// <returns>A <see cref="IQueryable"/> where each element represents a projection over a group and its key.</returns> /// <example> /// <code> /// var groupResult1 = queryable.GroupBy("NumberPropertyAsKey", "StringProperty"); /// var groupResult2 = queryable.GroupBy("new (NumberPropertyAsKey, StringPropertyAsKey)", "new (StringProperty1, StringProperty2)"); /// </code> /// </example> public static IQueryable GroupBy(this IQueryable source, ParsingConfig config, string keySelector, string resultSelector) { return GroupBy(source, config, keySelector, resultSelector, null, null); } /// <inheritdoc cref="GroupBy(IQueryable, ParsingConfig, string, string)"/> public static IQueryable GroupBy(this IQueryable source, string keySelector, string resultSelector) { return GroupBy(source, ParsingConfig.Default, keySelector, resultSelector); } /// <summary> /// Groups the elements of a sequence according to a specified key string function /// and creates a result value from each group and its key. /// </summary> /// <param name="source">A <see cref="IQueryable"/> whose elements to group.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="keySelector">A string expression to specify the key for each element.</param> /// <param name="resultSelector">A string expression to specify a result value from each group.</param> /// <param name="equalityComparer">The comparer to use.</param> /// <returns>A <see cref="IQueryable"/> where each element represents a projection over a group and its key.</returns> public static IQueryable GroupBy(this IQueryable source, ParsingConfig config, string keySelector, string resultSelector, IEqualityComparer equalityComparer) { return InternalGroupBy(source, config, keySelector, resultSelector, equalityComparer, null); } /// <inheritdoc cref="GroupBy(IQueryable, ParsingConfig, string, string, IEqualityComparer)"/> public static IQueryable GroupBy(this IQueryable source, string keySelector, string resultSelector, IEqualityComparer equalityComparer) { return GroupBy(source, ParsingConfig.Default, keySelector, resultSelector, equalityComparer); } /// <summary> /// Groups the elements of a sequence according to a specified key string function /// and creates a result value from each group and its key. /// </summary> /// <param name="source">A <see cref="IQueryable"/> whose elements to group.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="keySelector">A string expression to specify the key for each element.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>A <see cref="IQueryable"/> where each element represents a projection over a group and its key.</returns> /// <example> /// <code> /// var groupResult1 = queryable.GroupBy("NumberPropertyAsKey"); /// var groupResult2 = queryable.GroupBy("new (NumberPropertyAsKey, StringPropertyAsKey)"); /// </code> /// </example> [PublicAPI] public static IQueryable GroupBy(this IQueryable source, ParsingConfig config, string keySelector, params object[]? args) { return InternalGroupBy(source, config, keySelector, null, args); } /// <summary> /// Groups the elements of a sequence according to a specified key string function /// and creates a result value from each group and its key. /// </summary> /// <param name="source">A <see cref="IQueryable"/> whose elements to group.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="keySelector">A string expression to specify the key for each element.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <param name="equalityComparer">The comparer to use.</param> /// <returns>A <see cref="IQueryable"/> where each element represents a projection over a group and its key.</returns> public static IQueryable GroupBy(this IQueryable source, ParsingConfig config, string keySelector, IEqualityComparer equalityComparer, params object[]? args) { return InternalGroupBy(source, config, keySelector, equalityComparer, args); } internal static IQueryable InternalGroupBy(IQueryable source, ParsingConfig config, string keySelector, IEqualityComparer? equalityComparer, params object[]? args) { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(keySelector, nameof(keySelector)); bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, source); LambdaExpression keyLambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, keySelector, args); Expression? optimized; if (equalityComparer == null) { optimized = OptimizeExpression(Expression.Call( typeof(Queryable), nameof(Queryable.GroupBy), new[] { source.ElementType, keyLambda.Body.Type }, source.Expression, Expression.Quote(keyLambda))); } else { var equalityComparerGenericType = typeof(IEqualityComparer<>).MakeGenericType(keyLambda.Body.Type); optimized = OptimizeExpression(Expression.Call( typeof(Queryable), nameof(Queryable.GroupBy), new[] { source.ElementType, keyLambda.Body.Type }, source.Expression, Expression.Quote(keyLambda), Expression.Constant(equalityComparer, equalityComparerGenericType))); } return source.Provider.CreateQuery(optimized); } /// <inheritdoc cref="GroupBy(IQueryable, ParsingConfig, string, object[])"/> [PublicAPI] public static IQueryable GroupBy(this IQueryable source, string keySelector, params object[]? args) { return GroupBy(source, ParsingConfig.Default, keySelector, args); } /// <inheritdoc cref="GroupBy(IQueryable, ParsingConfig, string, IEqualityComparer, object[])"/> public static IQueryable GroupBy(this IQueryable source, string keySelector, IEqualityComparer equalityComparer, params object[]? args) { return GroupBy(source, ParsingConfig.Default, keySelector, equalityComparer, args); } #endregion GroupBy #region GroupByMany /// <summary> /// Groups the elements of a sequence according to multiple specified key string functions /// and creates a result value from each group (and subgroups) and its key. /// </summary> /// <typeparam name="TElement"></typeparam> /// <param name="source">A <see cref="IEnumerable{T}"/> whose elements to group.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="keySelectors"><see cref="string"/> expressions to specify the keys for each element.</param> /// <returns>A <see cref="IEnumerable{T}"/> of type <see cref="GroupResult"/> where each element represents a projection over a group, its key, and its subgroups.</returns> public static IEnumerable<GroupResult> GroupByMany<TElement>(this IEnumerable<TElement> source, ParsingConfig config, params string[] keySelectors) { Check.NotNull(source); Check.NotNull(config); Check.HasNoNulls(keySelectors); var selectors = new List<Func<TElement, object>>(keySelectors.Length); bool createParameterCtor = true; foreach (var selector in keySelectors) { LambdaExpression l = DynamicExpressionParser.ParseLambda(config, createParameterCtor, typeof(TElement), typeof(object), selector); selectors.Add((Func<TElement, object>)l.Compile()); } return GroupByManyInternal(source, selectors.ToArray(), 0); } /// <inheritdoc cref="GroupByMany{TElement}(IEnumerable{TElement}, ParsingConfig, string[])"/> public static IEnumerable<GroupResult> GroupByMany<TElement>(this IEnumerable<TElement> source, params string[] keySelectors) { return GroupByMany(source, ParsingConfig.Default, keySelectors); } /// <summary> /// Groups the elements of a sequence according to multiple specified key functions /// and creates a result value from each group (and subgroups) and its key. /// </summary> /// <typeparam name="TElement"></typeparam> /// <param name="source">A <see cref="IEnumerable{T}"/> whose elements to group.</param> /// <param name="keySelectors">Lambda expressions to specify the keys for each element.</param> /// <returns>A <see cref="IEnumerable{T}"/> of type <see cref="GroupResult"/> where each element represents a projection over a group, its key, and its subgroups.</returns> public static IEnumerable<GroupResult> GroupByMany<TElement>(this IEnumerable<TElement> source, params Func<TElement, object>[] keySelectors) { Check.NotNull(source); Check.HasNoNulls(keySelectors); return GroupByManyInternal(source, keySelectors, 0); } private static IEnumerable<GroupResult> GroupByManyInternal<TElement>(IEnumerable<TElement> source, Func<TElement, object>[] keySelectors, int currentSelector) { if (currentSelector >= keySelectors.Length) { return null!; // TODO } var selector = keySelectors[currentSelector]; var result = source.GroupBy(selector).Select( g => new GroupResult { Key = g.Key, Count = g.Count(), Items = g, Subgroups = GroupByManyInternal(g, keySelectors, currentSelector + 1) }); return result; } #endregion GroupByMany #region GroupJoin /// <summary> /// Correlates the elements of two sequences based on equality of keys and groups the results. The default equality comparer is used to compare keys. /// </summary> /// <param name="outer">The first sequence to join.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="inner">The sequence to join to the first sequence.</param> /// <param name="outerKeySelector">A dynamic function to extract the join key from each element of the first sequence.</param> /// <param name="innerKeySelector">A dynamic function to extract the join key from each element of the second sequence.</param> /// <param name="resultSelector">A dynamic function to create a result element from an element from the first sequence and a collection of matching elements from the second sequence.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicates as parameters. Similar to the way String.Format formats strings.</param> /// <returns>An <see cref="IQueryable"/> obtained by performing a grouped join on two sequences.</returns> public static IQueryable GroupJoin(this IQueryable outer, ParsingConfig config, IEnumerable inner, string outerKeySelector, string innerKeySelector, string resultSelector, params object?[] args) { Check.NotNull(outer, nameof(outer)); Check.NotNull(config); Check.NotNull(inner, nameof(inner)); Check.NotEmpty(outerKeySelector, nameof(outerKeySelector)); Check.NotEmpty(innerKeySelector, nameof(innerKeySelector)); Check.NotEmpty(resultSelector, nameof(resultSelector)); Type outerType = outer.ElementType; Type innerType = inner.AsQueryable().ElementType; bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, outer); LambdaExpression outerSelectorLambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, outerType, null, outerKeySelector, args); LambdaExpression innerSelectorLambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, innerType, null, innerKeySelector, args); CheckOuterAndInnerTypes(config, createParameterCtor, outerType, innerType, outerKeySelector, innerKeySelector, ref outerSelectorLambda, ref innerSelectorLambda, args); ParameterExpression[] parameters = { ParameterExpressionHelper.CreateParameterExpression(outerType, "outer"), ParameterExpressionHelper.CreateParameterExpression(typeof(IEnumerable<>).MakeGenericType(innerType), "inner") }; LambdaExpression resultSelectorLambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, parameters, null, resultSelector, args); return outer.Provider.CreateQuery(Expression.Call( typeof(Queryable), nameof(Queryable.GroupJoin), new[] { outer.ElementType, innerType, outerSelectorLambda.Body.Type, resultSelectorLambda.Body.Type }, outer.Expression, inner.AsQueryable().Expression, Expression.Quote(outerSelectorLambda), Expression.Quote(innerSelectorLambda), Expression.Quote(resultSelectorLambda))); } /// <inheritdoc cref="GroupJoin(IQueryable, ParsingConfig, IEnumerable, string, string, string, object[])"/> public static IQueryable GroupJoin(this IQueryable outer, IEnumerable inner, string outerKeySelector, string innerKeySelector, string resultSelector, params object?[] args) { return GroupJoin(outer, ParsingConfig.Default, inner, outerKeySelector, innerKeySelector, resultSelector, args); } #endregion #region Join /// <summary> /// Correlates the elements of two sequences based on matching keys. The default equality comparer is used to compare keys. /// </summary> /// <param name="outer">The first sequence to join.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="inner">The sequence to join to the first sequence.</param> /// <param name="outerKeySelector">A dynamic function to extract the join key from each element of the first sequence.</param> /// <param name="innerKeySelector">A dynamic function to extract the join key from each element of the second sequence.</param> /// <param name="resultSelector">A dynamic function to create a result element from two matching elements.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicates as parameters. Similar to the way String.Format formats strings.</param> /// <returns>An <see cref="IQueryable"/> obtained by performing an inner join on two sequences.</returns> public static IQueryable Join(this IQueryable outer, ParsingConfig config, IEnumerable inner, string outerKeySelector, string innerKeySelector, string resultSelector, params object?[] args) { //path_to_url Check.NotNull(outer, nameof(outer)); Check.NotNull(config); Check.NotNull(inner, nameof(inner)); Check.NotEmpty(outerKeySelector, nameof(outerKeySelector)); Check.NotEmpty(innerKeySelector, nameof(innerKeySelector)); Check.NotEmpty(resultSelector, nameof(resultSelector)); Type outerType = outer.ElementType; Type innerType = inner.AsQueryable().ElementType; bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, outer); LambdaExpression outerSelectorLambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, outerType, null, outerKeySelector, args); LambdaExpression innerSelectorLambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, innerType, null, innerKeySelector, args); CheckOuterAndInnerTypes(config, createParameterCtor, outerType, innerType, outerKeySelector, innerKeySelector, ref outerSelectorLambda, ref innerSelectorLambda, args); ParameterExpression[] parameters = { ParameterExpressionHelper.CreateParameterExpression(outerType, "outer"), ParameterExpressionHelper.CreateParameterExpression(innerType, "inner") }; LambdaExpression resultSelectorLambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, parameters, null, resultSelector, args); var optimized = OptimizeExpression(Expression.Call( typeof(Queryable), "Join", new[] { outerType, innerType, outerSelectorLambda.Body.Type, resultSelectorLambda.Body.Type }, outer.Expression, // outer: The first sequence to join. inner.AsQueryable().Expression, // inner: The sequence to join to the first sequence. Expression.Quote(outerSelectorLambda), // outerKeySelector: A function to extract the join key from each element of the first sequence. Expression.Quote(innerSelectorLambda), // innerKeySelector: A function to extract the join key from each element of the second sequence. Expression.Quote(resultSelectorLambda) // resultSelector: A function to create a result element from two matching elements. )); return outer.Provider.CreateQuery(optimized); } /// <inheritdoc cref="Join(IQueryable, ParsingConfig, IEnumerable, string, string, string, object[])"/> public static IQueryable Join(this IQueryable outer, IEnumerable inner, string outerKeySelector, string innerKeySelector, string resultSelector, params object?[] args) { return Join(outer, ParsingConfig.Default, inner, outerKeySelector, innerKeySelector, resultSelector, args); } /// <summary> /// Correlates the elements of two sequences based on matching keys. The default equality comparer is used to compare keys. /// </summary> /// <typeparam name="TElement">The type of the elements of both sequences, and the result.</typeparam> /// <param name="outer">The first sequence to join.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="inner">The sequence to join to the first sequence.</param> /// <param name="outerKeySelector">A dynamic function to extract the join key from each element of the first sequence.</param> /// <param name="innerKeySelector">A dynamic function to extract the join key from each element of the second sequence.</param> /// <param name="resultSelector">A dynamic function to create a result element from two matching elements.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicates as parameters. Similar to the way String.Format formats strings.</param> /// <remarks>This overload only works on elements where both sequences and the resulting element match.</remarks> /// <returns>An <see cref="IQueryable{T}"/> that has elements of type TResult obtained by performing an inner join on two sequences.</returns> public static IQueryable<TElement> Join<TElement>(this IQueryable<TElement> outer, ParsingConfig config, IEnumerable<TElement> inner, string outerKeySelector, string innerKeySelector, string resultSelector, params object?[] args) { return (IQueryable<TElement>)Join(outer, config, (IEnumerable)inner, outerKeySelector, innerKeySelector, resultSelector, args); } /// <inheritdoc cref="Join{TElement}(IQueryable{TElement}, ParsingConfig, IEnumerable{TElement}, string, string, string, object[])"/> public static IQueryable<TElement> Join<TElement>(this IQueryable<TElement> outer, IEnumerable<TElement> inner, string outerKeySelector, string innerKeySelector, string resultSelector, params object?[] args) { return Join(outer, ParsingConfig.Default, inner, outerKeySelector, innerKeySelector, resultSelector, args); } #endregion Join #region Last private static readonly MethodInfo _last = QueryableMethodFinder.GetMethod(nameof(Queryable.Last)); private static readonly MethodInfo _lastPredicate = QueryableMethodFinder.GetMethodWithExpressionParameter(nameof(Queryable.Last)); /// <summary> /// Returns the last element of a sequence. /// </summary> /// <param name="source">The <see cref="IQueryable"/> to return the last element of.</param> /// <returns>The last element in source.</returns> #if NET35 public static object Last(this IQueryable source) #else public static dynamic Last(this IQueryable source) #endif { Check.NotNull(source); return Execute(_last, source); } /// <summary> /// Returns the last element of a sequence that satisfies a specified condition. /// </summary> /// <param name="source">The <see cref="IQueryable"/> to return the last element of.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>The first element in source that passes the test in predicate.</returns> #if NET35 public static object Last(this IQueryable source, ParsingConfig config, string predicate, params object?[] args) #else public static dynamic Last(this IQueryable source, ParsingConfig config, string predicate, params object?[] args) #endif { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(predicate); bool createParameterCtor = SupportsLinqToObjects(config, source); LambdaExpression lambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args); return Execute(_lastPredicate, source, lambda); } /// <inheritdoc cref="Last(IQueryable, ParsingConfig, string, object[])"/> #if NET35 public static object Last(this IQueryable source, string predicate, params object?[] args) #else public static dynamic Last(this IQueryable source, string predicate, params object?[] args) #endif { return Last(source, ParsingConfig.Default, predicate, args); } /// <summary> /// Returns the last element of a sequence that satisfies a specified condition. /// </summary> /// <param name="source">The <see cref="IQueryable"/> to return the last element of.</param> /// <param name="lambda">A cached Lambda Expression.</param> /// <returns>The first element in source that passes the test in predicate.</returns> #if NET35 public static object Last(this IQueryable source, LambdaExpression lambda) #else public static dynamic Last(this IQueryable source, LambdaExpression lambda) #endif { Check.NotNull(source); return Execute(_lastPredicate, source, lambda); } #endregion Last #region LastOrDefault private static readonly MethodInfo _lastDefault = QueryableMethodFinder.GetMethod(nameof(Queryable.LastOrDefault)); private static readonly MethodInfo _lastDefaultPredicate = QueryableMethodFinder.GetMethodWithExpressionParameter(nameof(Queryable.LastOrDefault)); /// <summary> /// Returns the last element of a sequence, or a default value if the sequence contains no elements. /// </summary> /// <param name="source">The <see cref="IQueryable"/> to return the last element of.</param> /// <returns>default if source is empty; otherwise, the last element in source.</returns> #if NET35 public static object LastOrDefault(this IQueryable source) #else public static dynamic LastOrDefault(this IQueryable source) #endif { Check.NotNull(source); return Execute(_lastDefault, source); } /// <summary> /// Returns the last element of a sequence that satisfies a specified condition, or a default value if the sequence contains no elements. /// </summary> /// <param name="source">The <see cref="IQueryable"/> to return the last element of.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>The first element in source that passes the test in predicate.</returns> #if NET35 public static object LastOrDefault(this IQueryable source, ParsingConfig config, string predicate, params object?[] args) #else public static dynamic LastOrDefault(this IQueryable source, ParsingConfig config, string predicate, params object?[] args) #endif { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(predicate); bool createParameterCtor = SupportsLinqToObjects(config, source); LambdaExpression lambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args); return Execute(_lastDefaultPredicate, source, lambda); } /// <inheritdoc cref="LastOrDefault(IQueryable, ParsingConfig, string, object[])"/> #if NET35 public static object LastOrDefault(this IQueryable source, string predicate, params object?[] args) #else public static dynamic LastOrDefault(this IQueryable source, string predicate, params object?[] args) #endif { return LastOrDefault(source, ParsingConfig.Default, predicate, args); } /// <summary> /// Returns the last element of a sequence that satisfies a specified condition, or a default value if the sequence contains no elements. /// </summary> /// <param name="source">The <see cref="IQueryable"/> to return the last element of.</param> /// <param name="lambda">A cached Lambda Expression.</param> /// <returns>The first element in source that passes the test in predicate.</returns> #if NET35 public static object LastOrDefault(this IQueryable source, LambdaExpression lambda) #else public static dynamic LastOrDefault(this IQueryable source, LambdaExpression lambda) #endif { Check.NotNull(source); return Execute(_lastDefaultPredicate, source, lambda); } #endregion LastOrDefault #region LongCount private static readonly MethodInfo _longCount = QueryableMethodFinder.GetMethod(nameof(Queryable.LongCount)); private static readonly MethodInfo _longCountPredicate = QueryableMethodFinder.GetMethodWithExpressionParameter(nameof(Queryable.LongCount)); /// <summary> /// Returns the number of elements in a sequence. /// </summary> /// <param name="source">The <see cref="IQueryable"/> that contains the elements to be counted.</param> /// <example> /// <code language="cs"> /// IQueryable queryable = employees.AsQueryable(); /// var result = queryable.LongCount(); /// </code> /// </example> /// <returns>The number of elements in the input sequence.</returns> public static long LongCount(this IQueryable source) { Check.NotNull(source); return Execute<long>(_longCount, source); } /// <summary> /// Returns the number of elements in a sequence. /// </summary> /// <param name="source">The <see cref="IQueryable"/> that contains the elements to be counted.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <example> /// <code language="cs"> /// IQueryable queryable = employees.AsQueryable(); /// var result1 = queryable.LongCount("Income > 50"); /// var result2 = queryable.LongCount("Income > @0", 50); /// var result3 = queryable.Select("Roles.LongCount()"); /// </code> /// </example> /// <returns>The number of elements in the specified sequence that satisfies a condition.</returns> [PublicAPI] public static long LongCount(this IQueryable source, ParsingConfig config, string predicate, params object?[] args) { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(predicate); bool createParameterCtor = SupportsLinqToObjects(config, source); LambdaExpression lambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args); return Execute<long>(_longCountPredicate, source, lambda); } /// <inheritdoc cref="LongCount(IQueryable, ParsingConfig, string, object[])"/> public static long LongCount(this IQueryable source, string predicate, params object?[] args) { return LongCount(source, ParsingConfig.Default, predicate, args); } /// <summary> /// Returns the number of elements in a sequence. /// </summary> /// <param name="source">The <see cref="IQueryable"/> that contains the elements to be counted.</param> /// <param name="lambda">A cached Lambda Expression.</param> /// <returns>The number of elements in the specified sequence that satisfies a condition.</returns> public static long LongCount(this IQueryable source, LambdaExpression lambda) { Check.NotNull(source); Check.NotNull(lambda); return Execute<long>(_longCountPredicate, source, lambda); } #endregion LongCount #region Max private static readonly MethodInfo _max = QueryableMethodFinder.GetMethod(nameof(Queryable.Max)); private static readonly MethodInfo _maxPredicate = QueryableMethodFinder.GetMethodWithExpressionParameter(nameof(Queryable.Max)); /// <summary> /// Computes the max element of a sequence. /// </summary> /// <param name="source">A sequence of values to calculate find the max for.</param> /// <example> /// <code language="cs"> /// IQueryable queryable = employees.AsQueryable(); /// var result1 = queryable.Max(); /// var result2 = queryable.Select("Roles.Max()"); /// </code> /// </example> /// <returns>The max element in the sequence.</returns> [PublicAPI] public static object Max(this IQueryable source) { Check.NotNull(source); return Execute(_max, source); } /// <summary> /// Computes the max element of a sequence. /// </summary> /// <param name="source">A sequence of values to calculate find the max for.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <example> /// <code language="cs"> /// IQueryable queryable = employees.AsQueryable(); /// var result = queryable.Max("Income"); /// </code> /// </example> /// <returns>The max element in the sequence.</returns> [PublicAPI] public static object Max(this IQueryable source, ParsingConfig config, string predicate, params object?[] args) { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(predicate); bool createParameterCtor = SupportsLinqToObjects(config, source); LambdaExpression lambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, typeof(object), predicate, args); return Execute(_maxPredicate, source, lambda); } /// <inheritdoc cref="Max(IQueryable, ParsingConfig, string, object[])"/> [PublicAPI] public static object Max(this IQueryable source, string predicate, params object?[] args) { return Max(source, ParsingConfig.Default, predicate, args); } /// <summary> /// Computes the max element of a sequence. /// </summary> /// <param name="source">A sequence of values to calculate find the max for.</param> /// <param name="lambda">A Lambda Expression.</param> /// <returns>The max element in the sequence.</returns> [PublicAPI] public static object Max(this IQueryable source, LambdaExpression lambda) { Check.NotNull(source); return Execute(_maxPredicate, source, lambda); } #endregion Max #region Min private static readonly MethodInfo _min = QueryableMethodFinder.GetMethod(nameof(Queryable.Min)); private static readonly MethodInfo _minPredicate = QueryableMethodFinder.GetMethodWithExpressionParameter(nameof(Queryable.Min)); /// <summary> /// Computes the min element of a sequence. /// </summary> /// <param name="source">A sequence of values to calculate find the min for.</param> /// <example> /// <code language="cs"> /// IQueryable queryable = employees.AsQueryable(); /// var result1 = queryable.Min(); /// var result2 = queryable.Select("Roles.Min()"); /// </code> /// </example> /// <returns>The min element in the sequence.</returns> [PublicAPI] public static object Min(this IQueryable source) { Check.NotNull(source); return Execute(_min, source); } /// <summary> /// Computes the min element of a sequence. /// </summary> /// <param name="source">A sequence of values to calculate find the min for.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <example> /// <code language="cs"> /// IQueryable queryable = employees.AsQueryable(); /// var result = queryable.Min("Income"); /// </code> /// </example> /// <returns>The min element in the sequence.</returns> [PublicAPI] public static object Min(this IQueryable source, ParsingConfig config, string predicate, params object?[] args) { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(predicate); bool createParameterCtor = SupportsLinqToObjects(config, source); LambdaExpression lambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, typeof(object), predicate, args); return Execute(_minPredicate, source, lambda); } /// <inheritdoc cref="Min(IQueryable, ParsingConfig, string, object[])"/> [PublicAPI] public static object Min(this IQueryable source, string predicate, params object?[] args) { return Min(source, ParsingConfig.Default, predicate, args); } /// <summary> /// Computes the min element of a sequence. /// </summary> /// <param name="source">A sequence of values to calculate find the min for.</param> /// <param name="lambda">A Lambda Expression.</param> /// <returns>The min element in the sequence.</returns> [PublicAPI] public static object Min(this IQueryable source, LambdaExpression lambda) { Check.NotNull(source); return Execute(_minPredicate, source, lambda); } #endregion Min #region OfType private static readonly MethodInfo _ofType = QueryableMethodFinder.GetGenericMethod(nameof(Queryable.OfType)); /// <summary> /// Filters the elements of an <see cref="IQueryable"/> based on a specified type. /// </summary> /// <param name="source">An <see cref="IQueryable"/> whose elements to filter.</param> /// <param name="type">The type to filter the elements of the sequence on.</param> /// <returns>A collection that contains the elements from source that have the type.</returns> public static IQueryable OfType(this IQueryable source, Type type) { Check.NotNull(source); Check.NotNull(type); var optimized = OptimizeExpression(Expression.Call(null, _ofType.MakeGenericMethod(type), new[] { source.Expression })); return source.Provider.CreateQuery(optimized); } /// <summary> /// Filters the elements of an <see cref="IQueryable"/> based on a specified type. /// </summary> /// <param name="source">An <see cref="IQueryable"/> whose elements to filter.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="typeName">The type to filter the elements of the sequence on.</param> /// <returns>A collection that contains the elements from source that have the type.</returns> public static IQueryable OfType(this IQueryable source, ParsingConfig config, string typeName) { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(typeName); var finder = new TypeFinder(config, new KeywordsHelper(config)); Type type = finder.FindTypeByName(typeName, null, true)!; return OfType(source, type); } /// <summary> /// Filters the elements of an <see cref="IQueryable"/> based on a specified type. /// </summary> /// <param name="source">An <see cref="IQueryable"/> whose elements to filter.</param> /// <param name="typeName">The type to filter the elements of the sequence on.</param> /// <returns>A collection that contains the elements from source that have the type.</returns> public static IQueryable OfType(this IQueryable source, string typeName) { return OfType(source, ParsingConfig.Default, typeName); } #endregion OfType #region OrderBy /// <summary> /// Sorts the elements of a sequence in ascending or descending order according to a key. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">A sequence of values to order.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="ordering">An expression string to indicate values to order by.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>A <see cref="IQueryable{T}"/> whose elements are sorted according to the specified <paramref name="ordering"/>.</returns> /// <example> /// <code> /// <![CDATA[ /// var resultSingle = queryable.OrderBy<User>("NumberProperty"); /// var resultSingleDescending = queryable.OrderBy<User>("NumberProperty DESC"); /// var resultMultiple = queryable.OrderBy<User>("NumberProperty, StringProperty"); /// ]]> /// </code> /// </example> public static IOrderedQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, ParsingConfig config, string ordering, params object?[] args) { return (IOrderedQueryable<TSource>)OrderBy((IQueryable)source, config, ordering, args); } /// <inheritdoc cref="OrderBy{TSource}(IQueryable{TSource}, ParsingConfig, string, object[])"/> public static IOrderedQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, string ordering, params object?[] args) { return OrderBy(source, ParsingConfig.Default, ordering, args); } /// <summary> /// Sorts the elements of a sequence in ascending or descending order according to a key. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">A sequence of values to order.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="ordering">An expression string to indicate values to order by.</param> /// <param name="comparer">The comparer to use.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>A <see cref="IQueryable{T}"/> whose elements are sorted according to the specified <paramref name="ordering"/>.</returns> public static IOrderedQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, ParsingConfig config, string ordering, IComparer comparer, params object?[] args) { return (IOrderedQueryable<TSource>)InternalOrderBy(source, config, ordering, comparer, args); } /// <summary> /// Sorts the elements of a sequence in ascending or descending order according to a key. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">A sequence of values to order.</param> /// <param name="ordering">An expression string to indicate values to order by.</param> /// <param name="comparer">The comparer to use.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>A <see cref="IQueryable{T}"/> whose elements are sorted according to the specified <paramref name="ordering"/>.</returns> public static IOrderedQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, string ordering, IComparer comparer, params object?[] args) { return OrderBy(source, ParsingConfig.Default, ordering, comparer, args); } /// <summary> /// Sorts the elements of a sequence in ascending or descending order according to a key. /// </summary> /// <param name="source">A sequence of values to order.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="ordering">An expression string to indicate values to order by.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>A <see cref="IQueryable"/> whose elements are sorted according to the specified <paramref name="ordering"/>.</returns> /// <example> /// <code> /// var resultSingle = queryable.OrderBy("NumberProperty"); /// var resultSingleDescending = queryable.OrderBy("NumberProperty DESC"); /// var resultMultiple = queryable.OrderBy("NumberProperty, StringProperty DESC"); /// </code> /// </example> public static IOrderedQueryable OrderBy(this IQueryable source, ParsingConfig config, string ordering, params object?[] args) { if (args.Length > 0 && args[0] != null && args[0]!.GetType().GetInterfaces().Any(i => i.Name.Contains("IComparer`1"))) { return InternalOrderBy(source, ParsingConfig.Default, ordering, args[0]!, args); } return InternalOrderBy(source, config, ordering, null, args); } /// <summary> /// Sorts the elements of a sequence in ascending or descending order according to a key. /// </summary> /// <param name="source">A sequence of values to order.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="ordering">An expression string to indicate values to order by.</param> /// <param name="comparer">The comparer to use.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>A <see cref="IQueryable"/> whose elements are sorted according to the specified <paramref name="ordering"/>.</returns> public static IOrderedQueryable OrderBy(this IQueryable source, ParsingConfig config, string ordering, IComparer comparer, params object?[] args) { return InternalOrderBy(source, config, ordering, comparer, args); } internal static IOrderedQueryable InternalOrderBy(IQueryable source, ParsingConfig config, string ordering, object? comparer, params object?[] args) { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(ordering, nameof(ordering)); ParameterExpression[] parameters = { ParameterExpressionHelper.CreateParameterExpression(source.ElementType, string.Empty, config.RenameEmptyParameterExpressionNames) }; ExpressionParser parser = new ExpressionParser(parameters, ordering, args, config); IList<DynamicOrdering> dynamicOrderings = parser.ParseOrdering(); Expression queryExpr = source.Expression; foreach (DynamicOrdering dynamicOrdering in dynamicOrderings) { if (comparer == null) { queryExpr = Expression.Call( typeof(Queryable), dynamicOrdering.MethodName, new[] { source.ElementType, dynamicOrdering.Selector.Type }, queryExpr, Expression.Quote(Expression.Lambda(dynamicOrdering.Selector, parameters))); } else { var comparerGenericType = typeof(IComparer<>).MakeGenericType(dynamicOrdering.Selector.Type); ConstantExpression constant; if (comparerGenericType.IsInstanceOfType(comparer)) { constant = Expression.Constant(comparer, comparerGenericType); } else { #if !UAP10_0 var newType = DynamicClassFactory.CreateGenericComparerType(comparerGenericType, comparer.GetType()); constant = Expression.Constant(Activator.CreateInstance(newType), comparerGenericType); #else constant = Expression.Constant(comparer, comparerGenericType); #endif } queryExpr = Expression.Call( typeof(Queryable), dynamicOrdering.MethodName, new[] { source.ElementType, dynamicOrdering.Selector.Type }, queryExpr, Expression.Quote(Expression.Lambda(dynamicOrdering.Selector, parameters)), constant); } } var optimized = OptimizeExpression(queryExpr); return (IOrderedQueryable)source.Provider.CreateQuery(optimized); } /// <inheritdoc cref="OrderBy(IQueryable, ParsingConfig, string, object[])"/> public static IOrderedQueryable OrderBy(this IQueryable source, string ordering, params object?[] args) { return OrderBy(source, ParsingConfig.Default, ordering, args); } /// <inheritdoc cref="OrderBy(IQueryable, ParsingConfig, string, IComparer, object[])"/> public static IOrderedQueryable OrderBy(this IQueryable source, string ordering, IComparer comparer, params object?[] args) { return OrderBy(source, ParsingConfig.Default, ordering, comparer, args); } #endregion OrderBy #region Page/PageResult /// <summary> /// Returns the elements as paged. /// </summary> /// <param name="source">The IQueryable to return elements from.</param> /// <param name="page">The page to return.</param> /// <param name="pageSize">The number of elements per page.</param> /// <returns>A <see cref="IQueryable"/> that contains the paged elements.</returns> public static IQueryable Page(this IQueryable source, int page, int pageSize) { Check.NotNull(source); Check.Condition(page, p => p > 0, nameof(page)); Check.Condition(pageSize, ps => ps > 0, nameof(pageSize)); return source.Skip((page - 1) * pageSize).Take(pageSize); } /// <summary> /// Returns the elements as paged. /// </summary> /// <typeparam name="TSource">The type of the source.</typeparam> /// <param name="source">The IQueryable to return elements from.</param> /// <param name="page">The page to return.</param> /// <param name="pageSize">The number of elements per page.</param> /// <returns>A <see cref="IQueryable{TSource}"/> that contains the paged elements.</returns> public static IQueryable<TSource> Page<TSource>(this IQueryable<TSource> source, int page, int pageSize) { Check.NotNull(source); Check.Condition(page, p => p > 0, nameof(page)); Check.Condition(pageSize, ps => ps > 0, nameof(pageSize)); return Queryable.Take(Queryable.Skip(source, (page - 1) * pageSize), pageSize); } /// <summary> /// Returns the elements as paged and include the CurrentPage, PageCount, PageSize and RowCount. /// </summary> /// <param name="source">The IQueryable to return elements from.</param> /// <param name="page">The page to return.</param> /// <param name="pageSize">The number of elements per page.</param> /// <param name="rowCount">If this optional parameter has been defined, this value is used as the RowCount instead of executing a Linq `Count()`.</param> /// <returns>PagedResult</returns> public static PagedResult PageResult(this IQueryable source, int page, int pageSize, int? rowCount = null) { Check.NotNull(source); Check.Condition(page, p => p > 0, nameof(page)); Check.Condition(pageSize, ps => ps > 0, nameof(pageSize)); Check.Condition(rowCount, rc => rc == null || rc >= 0, nameof(rowCount)); var result = new PagedResult { CurrentPage = page, PageSize = pageSize, RowCount = rowCount ?? source.Count() }; result.PageCount = (int)Math.Ceiling((double)result.RowCount / pageSize); result.Queryable = Page(source, page, pageSize); return result; } /// <summary> /// Returns the elements as paged and include the CurrentPage, PageCount, PageSize and RowCount. /// </summary> /// <typeparam name="TSource">The type of the source.</typeparam> /// <param name="source">The IQueryable to return elements from.</param> /// <param name="page">The page to return.</param> /// <param name="pageSize">The number of elements per page.</param> /// <param name="rowCount">If this optional parameter has been defined, this value is used as the RowCount instead of executing a Linq `Count()`.</param> /// <returns>PagedResult{TSource}</returns> public static PagedResult<TSource> PageResult<TSource>(this IQueryable<TSource> source, int page, int pageSize, int? rowCount = null) { Check.NotNull(source); Check.Condition(page, p => p > 0, nameof(page)); Check.Condition(pageSize, ps => ps > 0, nameof(pageSize)); Check.Condition(rowCount, rc => rc == null || rc >= 0, nameof(rowCount)); var result = new PagedResult<TSource> { CurrentPage = page, PageSize = pageSize, RowCount = rowCount ?? Queryable.Count(source) }; result.PageCount = (int)Math.Ceiling((double)result.RowCount / pageSize); result.Queryable = Page(source, page, pageSize); return result; } #endregion Page/PageResult #region Reverse /// <summary> /// Inverts the order of the elements in a sequence. /// </summary> /// <param name="source">A sequence of values to reverse.</param> /// <returns>A <see cref="IQueryable"/> whose elements correspond to those of the input sequence in reverse order.</returns> public static IQueryable Reverse(this IQueryable source) { Check.NotNull(source); return Queryable.Reverse((IQueryable<object>)source); } #endregion Reverse #region Select /// <summary> /// Projects each element of a sequence into a new form. /// </summary> /// <param name="source">A sequence of values to project.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="selector">A projection string expression to apply to each element.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>An <see cref="IQueryable"/> whose elements are the result of invoking a projection string on each element of source.</returns> /// <example> /// <code> /// var singleField = queryable.Select("StringProperty"); /// var dynamicObject = queryable.Select("new (StringProperty1, StringProperty2 as OtherStringPropertyName)"); /// </code> /// </example> public static IQueryable Select(this IQueryable source, ParsingConfig config, string selector, params object?[] args) { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(selector, nameof(selector)); bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, source); LambdaExpression lambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, selector, args); var optimized = OptimizeExpression(Expression.Call( typeof(Queryable), nameof(Queryable.Select), new[] { source.ElementType, lambda.Body.Type }, source.Expression, Expression.Quote(lambda)) ); return source.Provider.CreateQuery(optimized); } /// <inheritdoc cref="Select(IQueryable, ParsingConfig, string, object[])"/> public static IQueryable Select(this IQueryable source, string selector, params object?[] args) { return Select(source, ParsingConfig.Default, selector, args); } /// <summary> /// Projects each element of a sequence into a new class of type TResult. /// Details see <see href="path_to_url"/>. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="source">A sequence of values to project.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="selector">A projection string expression to apply to each element.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters.</param> /// <returns>An <see cref="IQueryable{TResult}"/> whose elements are the result of invoking a projection string on each element of source.</returns> /// <example> /// <code language="cs"> /// <![CDATA[ /// var users = queryable.Select<User>("new (Username, Pwd as Password)"); /// ]]> /// </code> /// </example> public static IQueryable<TResult> Select<TResult>(this IQueryable source, ParsingConfig config, string selector, params object?[] args) { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(selector, nameof(selector)); bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, source); LambdaExpression lambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, typeof(TResult), selector, args); var methodCallExpression = Expression.Call( typeof(Queryable), nameof(Queryable.Select), new[] { source.ElementType, typeof(TResult) }, source.Expression, Expression.Quote(lambda) ); var optimized = OptimizeExpression(methodCallExpression); return source.Provider.CreateQuery<TResult>(optimized); } /// <inheritdoc cref="Select{TResult}(IQueryable, ParsingConfig, string, object[])"/> public static IQueryable<TResult> Select<TResult>(this IQueryable source, string selector, params object?[] args) { return Select<TResult>(source, ParsingConfig.Default, selector, args); } /// <summary> /// Projects each element of a sequence into a new class of type TResult. /// Details see path_to_url /// </summary> /// <param name="source">A sequence of values to project.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="resultType">The result type.</param> /// <param name="selector">A projection string expression to apply to each element.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters.</param> /// <returns>An <see cref="IQueryable"/> whose elements are the result of invoking a projection string on each element of source.</returns> /// <example> /// <code> /// var users = queryable.Select(typeof(User), "new (Username, Pwd as Password)"); /// </code> /// </example> public static IQueryable Select(this IQueryable source, ParsingConfig config, Type resultType, string selector, params object?[] args) { Check.NotNull(source); Check.NotNull(config); Check.NotNull(resultType, nameof(resultType)); Check.NotEmpty(selector, nameof(selector)); bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, source); LambdaExpression lambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, resultType, selector, args); var optimized = OptimizeExpression(Expression.Call( typeof(Queryable), nameof(Queryable.Select), new[] { source.ElementType, resultType }, source.Expression, Expression.Quote(lambda))); return source.Provider.CreateQuery(optimized); } /// <inheritdoc cref="Select(IQueryable, ParsingConfig, Type, string, object[])"/> public static IQueryable Select(this IQueryable source, Type resultType, string selector, params object?[] args) { return Select(source, ParsingConfig.Default, resultType, selector, args); } #endregion Select #region SelectMany /// <summary> /// Projects each element of a sequence to an <see cref="IQueryable"/> and combines the resulting sequences into one sequence. /// </summary> /// <param name="source">A sequence of values to project.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="selector">A projection string expression to apply to each element.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>An <see cref="IQueryable"/> whose elements are the result of invoking a one-to-many projection function on each element of the input sequence.</returns> /// <example> /// <code> /// var roles = users.SelectMany("Roles"); /// </code> /// </example> public static IQueryable SelectMany(this IQueryable source, ParsingConfig config, string selector, params object?[] args) { return SelectManyInternal(source, config, null, selector, args); } /// <inheritdoc cref="SelectMany(IQueryable, ParsingConfig, string, object[])"/> public static IQueryable SelectMany(this IQueryable source, string selector, params object?[] args) { return SelectMany(source, ParsingConfig.Default, selector, args); } /// <summary> /// Projects each element of a sequence to an <see cref="IQueryable"/> and combines the resulting sequences into one sequence. /// </summary> /// <param name="source">A sequence of values to project.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="selector">A projection string expression to apply to each element.</param> /// <param name="resultType">The result type.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>An <see cref="IQueryable"/> whose elements are the result of invoking a one-to-many projection function on each element of the input sequence.</returns> /// <example> /// <code> /// var permissions = users.SelectMany(typeof(Permission), "Roles.SelectMany(Permissions)"); /// </code> /// </example> public static IQueryable SelectMany(this IQueryable source, ParsingConfig config, Type resultType, string selector, params object?[] args) { Check.NotNull(source); Check.NotNull(config); Check.NotNull(resultType, nameof(resultType)); Check.NotEmpty(selector, nameof(selector)); return SelectManyInternal(source, config, resultType, selector, args); } /// <inheritdoc cref="SelectMany(IQueryable, ParsingConfig, Type, string, object[])"/> public static IQueryable SelectMany(this IQueryable source, Type resultType, string selector, params object?[] args) { return SelectMany(source, ParsingConfig.Default, resultType, selector, args); } private static IQueryable SelectManyInternal(IQueryable source, ParsingConfig config, Type? resultType, string selector, params object?[] args) { bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, source); LambdaExpression lambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, selector, args); //Extra help to get SelectMany to work from StackOverflow Answer //path_to_url // if resultType is not specified, create one based on the lambda.Body.Type if (resultType == null) { // SelectMany assumes that lambda.Body.Type is a generic type and throws an exception on // lambda.Body.Type.GetGenericArguments()[0] when used over an array as GetGenericArguments() returns an empty array. if (lambda.Body.Type.IsArray) { // In case of an Array, get the type via GetElementType(). resultType = lambda.Body.Type.GetElementType(); } else { var genericArguments = lambda.Body.Type.GetGenericArguments(); resultType = genericArguments.Any() ? genericArguments[0] : typeof(object); } } //we have to adjust to lambda to return an IEnumerable<T> instead of whatever the actual property is. Type enumerableType = typeof(IEnumerable<>).MakeGenericType(resultType); Type inputType = source.Expression.Type.GetTypeInfo().GetGenericTypeArguments()[0]; Type delegateType = typeof(Func<,>).MakeGenericType(inputType, enumerableType); lambda = Expression.Lambda(delegateType, lambda.Body, lambda.Parameters); var optimized = OptimizeExpression(Expression.Call( typeof(Queryable), nameof(Queryable.SelectMany), new[] { source.ElementType, resultType }, source.Expression, Expression.Quote(lambda)) ); return source.Provider.CreateQuery(optimized); } /// <summary> /// Projects each element of a sequence to an <see cref="IQueryable{TResult}"/> and combines the resulting sequences into one sequence. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="source">A sequence of values to project.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="selector">A projection string expression to apply to each element.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>An <see cref="IQueryable{TResult}"/> whose elements are the result of invoking a one-to-many projection function on each element of the input sequence.</returns> /// <example> /// <code> /// <![CDATA[ /// var permissions = users.SelectMany<Permission>("Roles.SelectMany(Permissions)"); /// ]]> /// </code> /// </example> public static IQueryable<TResult> SelectMany<TResult>(this IQueryable source, ParsingConfig config, string selector, params object?[] args) { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(selector, nameof(selector)); bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, source); LambdaExpression lambda = DynamicExpressionParser.ParseLambda(createParameterCtor, source.ElementType, null, selector, args); //we have to adjust to lambda to return an IEnumerable<T> instead of whatever the actual property is. Type inputType = source.Expression.Type.GetTypeInfo().GetGenericTypeArguments()[0]; Type enumerableType = typeof(IEnumerable<>).MakeGenericType(typeof(TResult)); Type delegateType = typeof(Func<,>).MakeGenericType(inputType, enumerableType); lambda = Expression.Lambda(delegateType, lambda.Body, lambda.Parameters); var optimized = OptimizeExpression(Expression.Call( typeof(Queryable), nameof(Queryable.SelectMany), new[] { source.ElementType, typeof(TResult) }, source.Expression, Expression.Quote(lambda)) ); return source.Provider.CreateQuery<TResult>(optimized); } /// <inheritdoc cref="SelectMany{TResult}(IQueryable, ParsingConfig, string, object[])"/> public static IQueryable<TResult> SelectMany<TResult>(this IQueryable source, string selector, params object?[] args) { return SelectMany<TResult>(source, ParsingConfig.Default, selector, args); } /// <summary> /// Projects each element of a sequence to an <see cref="IQueryable"/> /// and invokes a result selector function on each element therein. The resulting /// values from each intermediate sequence are combined into a single, one-dimensional /// sequence and returned. /// </summary> /// <param name="source">A sequence of values to project.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="collectionSelector">A projection function to apply to each element of the input sequence.</param> /// <param name="resultSelector">A projection function to apply to each element of each intermediate sequence. Should only use x and y as parameter names.</param> /// <param name="collectionSelectorArgs">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <param name="resultSelectorArgs">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns> /// An <see cref="IQueryable"/> whose elements are the result of invoking the one-to-many /// projection function <paramref name="collectionSelector"/> on each element of source and then mapping /// each of those sequence elements and their corresponding source element to a result element. /// </returns> /// <example> /// <code> /// <![CDATA[ /// // TODO /// ]]> /// </code> /// </example> public static IQueryable SelectMany(this IQueryable source, ParsingConfig config, string collectionSelector, string resultSelector, object[]? collectionSelectorArgs = null, params object[]? resultSelectorArgs) { return SelectMany(source, collectionSelector, resultSelector, "x", "y", collectionSelectorArgs, resultSelectorArgs); } /// <inheritdoc cref="SelectMany(IQueryable, ParsingConfig, string, string, string, string, object[], object[])"/> public static IQueryable SelectMany(this IQueryable source, string collectionSelector, string resultSelector, object[]? collectionSelectorArgs = null, params object[]? resultSelectorArgs) { return SelectMany(source, ParsingConfig.Default, collectionSelector, resultSelector, "x", "y", collectionSelectorArgs, resultSelectorArgs); } /// <summary> /// Projects each element of a sequence to an <see cref="IQueryable"/> /// and invokes a result selector function on each element therein. The resulting /// values from each intermediate sequence are combined into a single, one-dimensional /// sequence and returned. /// </summary> /// <param name="source">A sequence of values to project.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="collectionSelector">A projection function to apply to each element of the input sequence.</param> /// <param name="collectionParameterName">The name from collectionParameter to use. Default is x.</param> /// <param name="resultSelector">A projection function to apply to each element of each intermediate sequence.</param> /// <param name="resultParameterName">The name from resultParameterName to use. Default is y.</param> /// <param name="collectionSelectorArgs">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <param name="resultSelectorArgs">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns> /// An <see cref="IQueryable"/> whose elements are the result of invoking the one-to-many /// projection function <paramref name="collectionSelector"/> on each element of source and then mapping /// each of those sequence elements and their corresponding source element to a result element. /// </returns> /// <example> /// <code> /// <![CDATA[ /// // TODO /// ]]> /// </code> /// </example> public static IQueryable SelectMany( this IQueryable source, ParsingConfig config, string collectionSelector, string resultSelector, string collectionParameterName, string resultParameterName, object?[]? collectionSelectorArgs = null, params object[]? resultSelectorArgs) { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(collectionSelector, nameof(collectionSelector)); Check.NotEmpty(collectionParameterName, nameof(collectionParameterName)); Check.NotEmpty(resultSelector, nameof(resultSelector)); Check.NotEmpty(resultParameterName, nameof(resultParameterName)); bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, source); LambdaExpression sourceSelectLambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, collectionSelector, collectionSelectorArgs); //we have to adjust to lambda to return an IEnumerable<T> instead of whatever the actual property is. Type sourceLambdaInputType = source.Expression.Type.GetGenericArguments()[0]; Type sourceLambdaResultType = sourceSelectLambda.Body.Type.GetGenericArguments()[0]; Type sourceLambdaEnumerableType = typeof(IEnumerable<>).MakeGenericType(sourceLambdaResultType); Type sourceLambdaDelegateType = typeof(Func<,>).MakeGenericType(sourceLambdaInputType, sourceLambdaEnumerableType); sourceSelectLambda = Expression.Lambda(sourceLambdaDelegateType, sourceSelectLambda.Body, sourceSelectLambda.Parameters); //we have to create additional lambda for result selection ParameterExpression xParameter = ParameterExpressionHelper.CreateParameterExpression(source.ElementType, collectionParameterName, config.RenameEmptyParameterExpressionNames); ParameterExpression yParameter = ParameterExpressionHelper.CreateParameterExpression(sourceLambdaResultType, resultParameterName, config.RenameEmptyParameterExpressionNames); LambdaExpression resultSelectLambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, new[] { xParameter, yParameter }, null, resultSelector, resultSelectorArgs); Type resultLambdaResultType = resultSelectLambda.Body.Type; var optimized = OptimizeExpression(Expression.Call( typeof(Queryable), nameof(Queryable.SelectMany), new[] { source.ElementType, sourceLambdaResultType, resultLambdaResultType }, source.Expression, Expression.Quote(sourceSelectLambda), Expression.Quote(resultSelectLambda)) ); return source.Provider.CreateQuery(optimized); } /// <inheritdoc cref="SelectMany(IQueryable, ParsingConfig, string, string, string, string, object[], object[])"/> public static IQueryable SelectMany(this IQueryable source, string collectionSelector, string resultSelector, string collectionParameterName, string resultParameterName, object[]? collectionSelectorArgs = null, params object[]? resultSelectorArgs) { return SelectMany(source, ParsingConfig.Default, collectionSelector, resultSelector, collectionParameterName, resultParameterName, collectionSelectorArgs, resultSelectorArgs); } #endregion SelectMany #region Single/SingleOrDefault private static readonly MethodInfo _singlePredicate = QueryableMethodFinder.GetMethodWithExpressionParameter(nameof(Queryable.Single)); private static readonly MethodInfo _singleDefaultPredicate = QueryableMethodFinder.GetMethodWithExpressionParameter(nameof(Queryable.SingleOrDefault)); /// <summary> /// Returns the only element of a sequence, and throws an exception if there /// is not exactly one element in the sequence. /// </summary> /// <param name="source">A <see cref="IQueryable"/> to return the single element of.</param> /// <returns>The single element of the input sequence.</returns> #if NET35 public static object Single(this IQueryable source) #else public static dynamic Single(this IQueryable source) #endif { Check.NotNull(source); var optimized = OptimizeExpression(Expression.Call(typeof(Queryable), nameof(Queryable.Single), new[] { source.ElementType }, source.Expression)); return source.Provider.Execute(optimized); } /// <summary> /// Returns the only element of a sequence that satisfies a specified condition, and throws an exception if there /// is not exactly one element in the sequence. /// </summary> /// <param name="source">The <see cref="IQueryable"/> to return the last element of.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>The first element in source that passes the test in predicate.</returns> #if NET35 public static object Single(this IQueryable source, ParsingConfig config, string predicate, params object?[] args) #else public static dynamic Single(this IQueryable source, ParsingConfig config, string predicate, params object?[] args) #endif { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(predicate); bool createParameterCtor = SupportsLinqToObjects(config, source); LambdaExpression lambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args); return Execute(_singlePredicate, source, lambda); } /// <inheritdoc cref="Single(IQueryable, ParsingConfig, string, object[])"/> #if NET35 public static object Single(this IQueryable source, string predicate, params object?[] args) #else public static dynamic Single(this IQueryable source, string predicate, params object?[] args) #endif { return Single(source, ParsingConfig.Default, predicate, args); } /// <summary> /// Returns the only element of a sequence that satisfies a specified condition, and throws an exception if there /// is not exactly one element in the sequence. /// </summary> /// <param name="source">The <see cref="IQueryable"/> to return the last element of.</param> /// <param name="lambda">A cached Lambda Expression.</param> /// <returns>The first element in source that passes the test in predicate.</returns> #if NET35 public static object Single(this IQueryable source, LambdaExpression lambda) #else public static dynamic Single(this IQueryable source, LambdaExpression lambda) #endif { Check.NotNull(source); return Execute(_singlePredicate, source, lambda); } /// <summary> /// Returns the only element of a sequence, or a default value if the sequence /// is empty; this method throws an exception if there is more than one element /// in the sequence. /// </summary> /// <param name="source">A <see cref="IQueryable"/> to return the single element of.</param> /// <returns>The single element of the input sequence, or default if the sequence contains no elements.</returns> #if NET35 public static object SingleOrDefault(this IQueryable source) #else public static dynamic SingleOrDefault(this IQueryable source) #endif { Check.NotNull(source); var optimized = OptimizeExpression(Expression.Call(typeof(Queryable), nameof(Queryable.SingleOrDefault), new[] { source.ElementType }, source.Expression)); return source.Provider.Execute(optimized)!; } /// <summary> /// Returns the only element of a sequence that satisfies a specified condition or a default value if the sequence /// is empty; and throws an exception if there is not exactly one element in the sequence. /// </summary> /// <param name="source">The <see cref="IQueryable"/> to return the last element of.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>The first element in source that passes the test in predicate.</returns> #if NET35 public static object SingleOrDefault(this IQueryable source, ParsingConfig config, string predicate, params object?[] args) #else public static dynamic SingleOrDefault(this IQueryable source, ParsingConfig config, string predicate, params object?[] args) #endif { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(predicate); bool createParameterCtor = SupportsLinqToObjects(config, source); LambdaExpression lambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args); return Execute(_singleDefaultPredicate, source, lambda); } /// <inheritdoc cref="SingleOrDefault(IQueryable, ParsingConfig, string, object[])"/> #if NET35 public static object SingleOrDefault(this IQueryable source, string predicate, params object?[] args) #else public static dynamic SingleOrDefault(this IQueryable source, string predicate, params object?[] args) #endif { return SingleOrDefault(source, ParsingConfig.Default, predicate, args); } /// <summary> /// Returns the only element of a sequence that satisfies a specified condition or a default value if the sequence /// is empty; and throws an exception if there is not exactly one element in the sequence. /// </summary> /// <param name="source">The <see cref="IQueryable"/> to return the last element of.</param> /// <param name="lambda">A cached Lambda Expression.</param> /// <returns>The first element in source that passes the test in predicate.</returns> #if NET35 public static object SingleOrDefault(this IQueryable source, LambdaExpression lambda) #else public static dynamic SingleOrDefault(this IQueryable source, LambdaExpression lambda) #endif { Check.NotNull(source); Check.NotNull(lambda); return Execute(_singleDefaultPredicate, source, lambda); } #endregion Single/SingleOrDefault #region Skip private static readonly MethodInfo _skip = QueryableMethodFinder.GetMethod(nameof(Queryable.Skip), 1); /// <summary> /// Bypasses a specified number of elements in a sequence and then returns the remaining elements. /// </summary> /// <param name="source">A <see cref="IQueryable"/> to return elements from.</param> /// <param name="count">The number of elements to skip before returning the remaining elements.</param> /// <returns>A <see cref="IQueryable"/> that contains elements that occur after the specified index in the input sequence.</returns> public static IQueryable Skip(this IQueryable source, int count) { Check.NotNull(source); Check.Condition(count, x => x >= 0, nameof(count)); //no need to skip if count is zero if (count == 0) return source; return CreateQuery(_skip, source, Expression.Constant(count)); } #endregion Skip #region SkipWhile private static readonly MethodInfo _skipWhilePredicate = QueryableMethodFinder.GetMethodWithExpressionParameter(nameof(Queryable.SkipWhile)); /// <summary> /// Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements. /// </summary> /// <param name="source">A sequence to check for being empty.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <example> /// <code language="cs"> /// IQueryable queryable = employees.AsQueryable(); /// var result1 = queryable.SkipWhile("Income > 50"); /// var result2 = queryable.SkipWhile("Income > @0", 50); /// </code> /// </example> /// <returns>An <see cref="IQueryable"/> that contains elements from source starting at the first element in the linear series that does not pass the test specified by predicate.</returns> public static IQueryable SkipWhile(this IQueryable source, ParsingConfig config, string predicate, params object[]? args) { Check.NotNull(source); Check.NotNull(config); Check.NotNull(predicate, nameof(predicate)); bool createParameterCtor = SupportsLinqToObjects(config, source); LambdaExpression lambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args); return CreateQuery(_skipWhilePredicate, source, lambda); } /// <inheritdoc cref="SkipWhile(IQueryable, ParsingConfig, string, object[])"/> public static IQueryable SkipWhile(this IQueryable source, string predicate, params object[]? args) { return SkipWhile(source, ParsingConfig.Default, predicate, args); } #endregion SkipWhile #region Sum /// <summary> /// Computes the sum of a sequence of numeric values. /// </summary> /// <param name="source">A sequence of numeric values to calculate the sum of.</param> /// <example> /// <code language="cs"> /// IQueryable queryable = employees.AsQueryable(); /// var result1 = queryable.Sum(); /// var result2 = queryable.Select("Roles.Sum()"); /// </code> /// </example> /// <returns>The sum of the values in the sequence.</returns> [PublicAPI] public static object Sum(this IQueryable source) { Check.NotNull(source); var sum = QueryableMethodFinder.GetMethod(nameof(Queryable.Sum), source.ElementType); return Execute<object>(sum, source); } /// <summary> /// Computes the sum of a sequence of numeric values. /// </summary> /// <param name="source">A sequence of numeric values to calculate the sum of.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <example> /// <code language="cs"> /// IQueryable queryable = employees.AsQueryable(); /// var result = queryable.Sum("Income"); /// </code> /// </example> /// <returns>The sum of the values in the sequence.</returns> [PublicAPI] public static object Sum(this IQueryable source, ParsingConfig config, string predicate, params object?[] args) { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(predicate); bool createParameterCtor = SupportsLinqToObjects(config, source); LambdaExpression lambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args); var sumSelector = QueryableMethodFinder.GetMethod(nameof(Queryable.Sum), lambda.GetReturnType(), 1); return Execute<object>(sumSelector, source, lambda); } /// <inheritdoc cref="Sum(IQueryable, ParsingConfig, string, object[])"/> [PublicAPI] public static object Sum(this IQueryable source, string predicate, params object?[] args) { return Sum(source, ParsingConfig.Default, predicate, args); } /// <summary> /// Computes the sum of a sequence of numeric values. /// </summary> /// <param name="source">A sequence of numeric values to calculate the sum of.</param> /// <param name="lambda">A Lambda Expression.</param> /// <returns>The sum of the values in the sequence.</returns> [PublicAPI] public static object Sum(this IQueryable source, LambdaExpression lambda) { Check.NotNull(source); Check.NotNull(lambda); var sumSelector = QueryableMethodFinder.GetMethod(nameof(Queryable.Sum), lambda.GetReturnType(), 1); return Execute<object>(sumSelector, source, lambda); } #endregion Sum #region Take private static readonly MethodInfo _take = QueryableMethodFinder.GetMethodWithIntParameter(nameof(Queryable.Take)); /// <summary> /// Returns a specified number of contiguous elements from the start of a sequence. /// </summary> /// <param name="source">The sequence to return elements from.</param> /// <param name="count">The number of elements to return.</param> /// <returns>A <see cref="IQueryable"/> that contains the specified number of elements from the start of source.</returns> public static IQueryable Take(this IQueryable source, int count) { Check.NotNull(source); Check.Condition(count, x => x >= 0, nameof(count)); return CreateQuery(_take, source, Expression.Constant(count)); } #endregion Take #region TakeWhile private static readonly MethodInfo _takeWhilePredicate = QueryableMethodFinder.GetMethodWithExpressionParameter(nameof(Queryable.TakeWhile)); /// <summary> /// Returns elements from a sequence as long as a specified condition is true. /// </summary> /// <param name="source">A sequence to check for being empty.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <example> /// <code language="cs"> /// IQueryable queryable = employees.AsQueryable(); /// var result1 = queryable.TakeWhile("Income > 50"); /// var result2 = queryable.TakeWhile("Income > @0", 50); /// </code> /// </example> /// <returns>An <see cref="IQueryable"/> that contains elements from the input sequence occurring before the element at which the test specified by predicate no longer passes.</returns> public static IQueryable TakeWhile(this IQueryable source, ParsingConfig config, string predicate, params object?[] args) { Check.NotNull(source); Check.NotNull(config); Check.NotNull(predicate, nameof(predicate)); bool createParameterCtor = SupportsLinqToObjects(config, source); LambdaExpression lambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args); return CreateQuery(_takeWhilePredicate, source, lambda); } /// <inheritdoc cref="TakeWhile(IQueryable, ParsingConfig, string, object[])"/> public static IQueryable TakeWhile(this IQueryable source, string predicate, params object?[] args) { return TakeWhile(source, ParsingConfig.Default, predicate, args); } #endregion TakeWhile #region ThenBy /// <summary> /// Performs a subsequent ordering of the elements in a sequence in ascending order according to a key. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">A sequence of values to order.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="ordering">An expression string to indicate values to order by.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>A <see cref="IOrderedQueryable{T}"/> whose elements are sorted according to the specified <paramref name="ordering"/>.</returns> /// <example> /// <code> /// <![CDATA[ /// var result = queryable.OrderBy<User>("LastName"); /// var resultSingle = result.ThenBy<User>("NumberProperty"); /// var resultSingleDescending = result.ThenBy<User>("NumberProperty DESC"); /// var resultMultiple = result.ThenBy<User>("NumberProperty, StringProperty"); /// ]]> /// </code> /// </example> public static IOrderedQueryable<TSource> ThenBy<TSource>(this IOrderedQueryable<TSource> source, ParsingConfig config, string ordering, params object?[] args) { return (IOrderedQueryable<TSource>)ThenBy((IOrderedQueryable)source, config, ordering, args); } /// <inheritdoc cref="ThenBy{TSource}(IOrderedQueryable{TSource}, ParsingConfig, string, object[])"/> public static IOrderedQueryable<TSource> ThenBy<TSource>(this IOrderedQueryable<TSource> source, string ordering, params object?[] args) { return ThenBy(source, ParsingConfig.Default, ordering, args); } /// <summary> /// Performs a subsequent ordering of the elements in a sequence in ascending order according to a key. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">A sequence of values to order.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="ordering">An expression string to indicate values to order by.</param> /// <param name="comparer">The comparer to use.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>A <see cref="IOrderedQueryable{T}"/> whose elements are sorted according to the specified <paramref name="ordering"/>.</returns> public static IOrderedQueryable<TSource> ThenBy<TSource>(this IOrderedQueryable<TSource> source, ParsingConfig config, string ordering, IComparer comparer, params object?[] args) { return (IOrderedQueryable<TSource>)InternalThenBy(source, config, ordering, comparer, args); } /// <summary> /// Performs a subsequent ordering of the elements in a sequence in ascending order according to a key. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">A sequence of values to order.</param> /// <param name="ordering">An expression string to indicate values to order by.</param> /// <param name="comparer">The comparer to use.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>A <see cref="IOrderedQueryable{T}"/> whose elements are sorted according to the specified <paramref name="ordering"/>.</returns> public static IOrderedQueryable<TSource> ThenBy<TSource>(this IOrderedQueryable<TSource> source, string ordering, IComparer comparer, params object?[] args) { return ThenBy(source, ParsingConfig.Default, ordering, comparer, args); } /// <summary> /// Performs a subsequent ordering of the elements in a sequence in ascending order according to a key. /// </summary> /// <param name="source">A sequence of values to order.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="ordering">An expression string to indicate values to order by.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>A <see cref="IQueryable"/> whose elements are sorted according to the specified <paramref name="ordering"/>.</returns> /// <example> /// <code> /// var result = queryable.OrderBy("LastName"); /// var resultSingle = result.OrderBy("NumberProperty"); /// var resultSingleDescending = result.OrderBy("NumberProperty DESC"); /// var resultMultiple = result.OrderBy("NumberProperty, StringProperty DESC"); /// </code> /// </example> public static IOrderedQueryable ThenBy(this IOrderedQueryable source, ParsingConfig config, string ordering, params object?[] args) { return InternalThenBy(source, config, ordering, null, args); } /// <summary> /// Performs a subsequent ordering of the elements in a sequence in ascending order according to a key. /// </summary> /// <param name="source">A sequence of values to order.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="ordering">An expression string to indicate values to order by.</param> /// <param name="comparer">The comparer to use.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>A <see cref="IQueryable"/> whose elements are sorted according to the specified <paramref name="ordering"/>.</returns> public static IOrderedQueryable ThenBy(this IOrderedQueryable source, ParsingConfig config, string ordering, IComparer comparer, params object?[] args) { return InternalThenBy(source, config, ordering, comparer, args); } internal static IOrderedQueryable InternalThenBy(IOrderedQueryable source, ParsingConfig config, string ordering, IComparer? comparer, params object?[] args) { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(ordering, nameof(ordering)); ParameterExpression[] parameters = { ParameterExpressionHelper.CreateParameterExpression(source.ElementType, string.Empty, config.RenameEmptyParameterExpressionNames) }; ExpressionParser parser = new ExpressionParser(parameters, ordering, args, config); IList<DynamicOrdering> dynamicOrderings = parser.ParseOrdering(forceThenBy: true); Expression queryExpr = source.Expression; foreach (DynamicOrdering dynamicOrdering in dynamicOrderings) { if (comparer == null) { queryExpr = Expression.Call( typeof(Queryable), dynamicOrdering.MethodName, new[] { source.ElementType, dynamicOrdering.Selector.Type }, queryExpr, Expression.Quote(Expression.Lambda(dynamicOrdering.Selector, parameters))); } else { var comparerGenericType = typeof(IComparer<>).MakeGenericType(dynamicOrdering.Selector.Type); queryExpr = Expression.Call( typeof(Queryable), dynamicOrdering.MethodName, new[] { source.ElementType, dynamicOrdering.Selector.Type }, queryExpr, Expression.Quote(Expression.Lambda(dynamicOrdering.Selector, parameters)), Expression.Constant(comparer, comparerGenericType)); } } var optimized = OptimizeExpression(queryExpr); return (IOrderedQueryable)source.Provider.CreateQuery(optimized); } /// <inheritdoc cref="ThenBy(IOrderedQueryable, ParsingConfig, string, object[])"/> public static IOrderedQueryable ThenBy(this IOrderedQueryable source, string ordering, params object?[] args) { return ThenBy(source, ParsingConfig.Default, ordering, args); } /// <inheritdoc cref="ThenBy(IOrderedQueryable, ParsingConfig, string, IComparer, object[])"/> public static IOrderedQueryable ThenBy(this IOrderedQueryable source, string ordering, IComparer comparer, params object?[] args) { return ThenBy(source, ParsingConfig.Default, ordering, comparer, args); } #endregion OrderBy #region Where /// <summary> /// Filters a sequence of values based on a predicate. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <param name="source">A <see cref="IQueryable{TSource}"/> to filter.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="predicate">An expression string to test each element for a condition.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>A <see cref="IQueryable{TSource}"/> that contains elements from the input sequence that satisfy the condition specified by predicate.</returns> /// <example> /// <code language="cs"> /// var result1 = queryable.Where("NumberProperty = 1"); /// var result2 = queryable.Where("NumberProperty = @0", 1); /// var result3 = queryable.Where("StringProperty = null"); /// var result4 = queryable.Where("StringProperty = \"abc\""); /// var result5 = queryable.Where("StringProperty = @0", "abc"); /// </code> /// </example> public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, ParsingConfig config, string predicate, params object?[] args) { return (IQueryable<TSource>)Where((IQueryable)source, config, predicate, args); } /// <inheritdoc cref="Where{TSource}(IQueryable{TSource}, ParsingConfig, string, object[])"/> public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, string predicate, params object?[] args) { return Where(source, ParsingConfig.Default, predicate, args); } /// <summary> /// Filters a sequence of values based on a predicate. /// </summary> /// <param name="source">A <see cref="IQueryable"/> to filter.</param> /// <param name="config">The <see cref="ParsingConfig"/>.</param> /// <param name="predicate">An expression string to test each element for a condition.</param> /// <param name="args">An object array that contains zero or more objects to insert into the predicate as parameters. Similar to the way String.Format formats strings.</param> /// <returns>A <see cref="IQueryable"/> that contains elements from the input sequence that satisfy the condition specified by predicate.</returns> /// <example> /// <code> /// var result1 = queryable.Where("NumberProperty = 1"); /// var result2 = queryable.Where("NumberProperty = @0", 1); /// var result3 = queryable.Where("StringProperty = null"); /// var result4 = queryable.Where("StringProperty = \"abc\""); /// var result5 = queryable.Where("StringProperty = @0", "abc"); /// </code> /// </example> public static IQueryable Where(this IQueryable source, ParsingConfig config, string predicate, params object?[] args) { Check.NotNull(source); Check.NotNull(config); Check.NotEmpty(predicate); bool createParameterCtor = SupportsLinqToObjects(config, source); LambdaExpression lambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args); var optimized = OptimizeExpression(Expression.Call(typeof(Queryable), nameof(Queryable.Where), new[] { source.ElementType }, source.Expression, Expression.Quote(lambda))); return source.Provider.CreateQuery(optimized); } /// <inheritdoc cref="DynamicQueryableExtensions.Where(IQueryable, ParsingConfig, string, object[])"/> public static IQueryable Where(this IQueryable source, string predicate, params object?[] args) { return Where(source, ParsingConfig.Default, predicate, args); } /// <summary> /// Filters a sequence of values based on a predicate. /// </summary> /// <param name="source">A <see cref="IQueryable"/> to filter.</param> /// <param name="lambda">A cached Lambda Expression.</param> /// <returns>A <see cref="IQueryable"/> that contains elements from the input sequence that satisfy the condition specified by LambdaExpression.</returns> public static IQueryable Where(this IQueryable source, LambdaExpression lambda) { Check.NotNull(source); Check.NotNull(lambda); var optimized = OptimizeExpression(Expression.Call(typeof(Queryable), nameof(Queryable.Where), new[] { source.ElementType }, source.Expression, Expression.Quote(lambda))); return source.Provider.CreateQuery(optimized); } /// <inheritdoc cref="DynamicQueryableExtensions.Where(IQueryable, LambdaExpression)"/> public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, LambdaExpression lambda) { return (IQueryable<TSource>)Where((IQueryable)source, lambda); } #endregion #region Private Helpers private static bool SupportsLinqToObjects(ParsingConfig config, IQueryable query) { return config.QueryableAnalyzer.SupportsLinqToObjects(query); } private static void CheckOuterAndInnerTypes(ParsingConfig config, bool createParameterCtor, Type outerType, Type innerType, string outerKeySelector, string innerKeySelector, ref LambdaExpression outerSelectorLambda, ref LambdaExpression innerSelectorLambda, params object?[] args) { var outerSelectorReturnTypes = TypeHelper.GetSelfAndBaseTypes(outerSelectorLambda.Body.Type, true); var innerSelectorReturnTypes = TypeHelper.GetSelfAndBaseTypes(innerSelectorLambda.Body.Type, true); foreach (var outerSelectorReturnTypeInLoop in outerSelectorReturnTypes) { var outerSelectorBodyType = outerSelectorReturnTypeInLoop; foreach (var innerSelectorReturnTypeInLoop in innerSelectorReturnTypes) { var innerSelectorBodyType = innerSelectorReturnTypeInLoop; // If types are not the same, try to convert to Nullable and generate new LambdaExpression if (outerSelectorBodyType != innerSelectorBodyType) { if (TypeHelper.IsNullableType(outerSelectorReturnTypeInLoop) && !TypeHelper.IsNullableType(innerSelectorReturnTypeInLoop)) { innerSelectorBodyType = ExpressionParser.ToNullableType(innerSelectorReturnTypeInLoop); innerSelectorLambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, innerType, innerSelectorBodyType, innerKeySelector, args); } else if (!TypeHelper.IsNullableType(outerSelectorReturnTypeInLoop) && TypeHelper.IsNullableType(innerSelectorReturnTypeInLoop)) { outerSelectorBodyType = ExpressionParser.ToNullableType(outerSelectorReturnTypeInLoop); outerSelectorLambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, outerType, outerSelectorBodyType, outerKeySelector, args); } } if (outerSelectorBodyType == innerSelectorBodyType) { // Types are equal (maybe after converting to nullable or after lopping), return from method. return; } } } // If types are still not the same, throw an Exception throw new ParseException(string.Format(CultureInfo.CurrentCulture, Res.IncompatibleTypes, outerSelectorLambda.Body.Type, innerSelectorLambda.Body.Type), -1); } // Code below is based on path_to_url private static IQueryable CreateQuery(MethodInfo operatorMethodInfo, IQueryable source) { if (operatorMethodInfo.IsGenericMethod) { operatorMethodInfo = operatorMethodInfo.MakeGenericMethod(source.ElementType); } var optimized = OptimizeExpression(Expression.Call(null, operatorMethodInfo, source.Expression)); return source.Provider.CreateQuery(optimized); } private static IQueryable CreateQuery(MethodInfo operatorMethodInfo, IQueryable source, LambdaExpression expression) => CreateQuery(operatorMethodInfo, source, Expression.Quote(expression)); private static IQueryable CreateQuery(MethodInfo operatorMethodInfo, IQueryable source, Expression expression) { operatorMethodInfo = operatorMethodInfo.GetGenericArguments().Length == 2 ? operatorMethodInfo.MakeGenericMethod(source.ElementType, typeof(object)) : operatorMethodInfo.MakeGenericMethod(source.ElementType); return source.Provider.CreateQuery(Expression.Call(null, operatorMethodInfo, source.Expression, expression)); } private static object Execute(MethodInfo operatorMethodInfo, IQueryable source) { if (operatorMethodInfo.IsGenericMethod) { operatorMethodInfo = operatorMethodInfo.MakeGenericMethod(source.ElementType); } var optimized = OptimizeExpression(Expression.Call(null, operatorMethodInfo, source.Expression)); return source.Provider.Execute(optimized)!; } private static TResult Execute<TResult>(MethodInfo operatorMethodInfo, IQueryable source) { if (operatorMethodInfo.IsGenericMethod) { operatorMethodInfo = operatorMethodInfo.MakeGenericMethod(source.ElementType); } var optimized = OptimizeExpression(Expression.Call(null, operatorMethodInfo, source.Expression)); var result = source.Provider.Execute(optimized)!; return ConvertResultIfNeeded<TResult>(result); } private static object Execute(MethodInfo operatorMethodInfo, IQueryable source, LambdaExpression expression) => Execute(operatorMethodInfo, source, Expression.Quote(expression)); private static object Execute(MethodInfo operatorMethodInfo, IQueryable source, Expression expression) { operatorMethodInfo = operatorMethodInfo.GetGenericArguments().Length == 2 ? operatorMethodInfo.MakeGenericMethod(source.ElementType, typeof(object)) : operatorMethodInfo.MakeGenericMethod(source.ElementType); var optimized = OptimizeExpression(Expression.Call(null, operatorMethodInfo, source.Expression, expression)); return source.Provider.Execute(optimized)!; } private static TResult Execute<TResult>(MethodInfo operatorMethodInfo, IQueryable source, LambdaExpression expression) => Execute<TResult>(operatorMethodInfo, source, Expression.Quote(expression)); private static TResult Execute<TResult>(MethodInfo operatorMethodInfo, IQueryable source, Expression expression) { operatorMethodInfo = operatorMethodInfo.GetGenericArguments().Length == 2 ? operatorMethodInfo.MakeGenericMethod(source.ElementType, typeof(TResult)) : operatorMethodInfo.MakeGenericMethod(source.ElementType); var optimized = OptimizeExpression(Expression.Call(null, operatorMethodInfo, source.Expression, expression)); var result = source.Provider.Execute(optimized)!; return ConvertResultIfNeeded<TResult>(result); } private static TResult ConvertResultIfNeeded<TResult>(object result) { if (result.GetType() == typeof(TResult)) { return (TResult)result; } return (TResult?)Convert.ChangeType(result, typeof(TResult))!; } #endregion Private Helpers } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/DynamicQueryableExtensions.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
29,695
```smalltalk using System.ComponentModel; namespace System.Linq.Dynamic.Core.TypeConverters; internal interface ITypeConverterFactory { /// <summary> /// Returns a type converter for the specified type. /// </summary> /// <param name="type">The System.Type of the target component.</param> /// <returns>A System.ComponentModel.TypeConverter for the specified type.</returns> TypeConverter GetConverter(Type type); } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/TypeConverters/ITypeConverterFactory.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
85
```smalltalk #if NET6_0 using System.ComponentModel; using System.Globalization; namespace System.Linq.Dynamic.Core.TypeConverters; /// <summary> /// Based on path_to_url /// </summary> internal class TimeOnlyConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) { return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); } public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destinationType) { return destinationType == typeof(string) || base.CanConvertTo(context, destinationType); } public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value) { if (value is string s) { return TimeOnly.Parse(s, culture); } return base.ConvertFrom(context, culture, value); } public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { if (destinationType == typeof(string)) { return ((TimeOnly?)value)?.ToString(culture); } return base.ConvertTo(context, culture, value, destinationType); } public override bool IsValid(ITypeDescriptorContext? context, object? value) { return value is TimeOnly || base.IsValid(context, value); } } #endif ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/TypeConverters/TimeOnlyConverter.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
291
```smalltalk using System.ComponentModel; using System.Globalization; namespace System.Linq.Dynamic.Core.TypeConverters; internal class CustomDateTimeConverter : DateTimeOffsetConverter { /// <summary> /// Converts the specified object to a <see cref="DateTime"></see>. /// </summary> /// <param name="context">The date format context.</param> /// <param name="culture">The date culture.</param> /// <param name="value">The object to be converted.</param> /// <returns>A <see cref="Nullable{DateTime}"></see> that represents the specified object.</returns> /// <exception cref="NotSupportedException">The conversion cannot be performed.</exception> #if NET6_0_OR_GREATER public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value) #else public override object? ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) #endif { var dateTimeOffset = base.ConvertFrom(context, culture, value) as DateTimeOffset?; return dateTimeOffset?.UtcDateTime; } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/TypeConverters/CustomDateTimeConverter.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
222
```smalltalk namespace System.Linq.Dynamic.Core.CustomTypeProviders { /// <summary> /// Interface for providing functionality to find custom types for or resolve any type. /// Note that this interface will be marked obsolete in the next version. Use <see cref="IDynamicLinqCustomTypeProvider"/> instead. /// </summary> public interface IDynamicLinkCustomTypeProvider : IDynamicLinqCustomTypeProvider { } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/CustomTypeProviders/IDynamicLinkCustomTypeProvider.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
90
```smalltalk using System.Collections.Generic; using System.Reflection; namespace System.Linq.Dynamic.Core.CustomTypeProviders; /// <summary> /// Interface for providing functionality to find custom types for or resolve any type. /// </summary> public interface IDynamicLinqCustomTypeProvider { /// <summary> /// Returns a list of custom types that System.Linq.Dynamic.Core will understand. /// </summary> /// <returns>A <see cref="HashSet{Type}" /> list of custom types.</returns> HashSet<Type> GetCustomTypes(); /// <summary> /// Returns a list of custom extension methods that System.Linq.Dynamic.Core will understand. /// </summary> /// <returns>A list of custom extension methods that System.Linq.Dynamic.Core will understand.</returns> Dictionary<Type, List<MethodInfo>> GetExtensionMethods(); /// <summary> /// Resolve any type by fullname which is registered in the current application domain. /// </summary> /// <param name="typeName">The typename to resolve.</param> /// <returns>A resolved <see cref="Type"/> or null when not found.</returns> Type? ResolveType(string typeName); /// <summary> /// Resolve any type by the simple name which is registered in the current application domain. /// </summary> /// <param name="simpleTypeName">The typename to resolve.</param> /// <returns>A resolved <see cref="Type"/> or null when not found.</returns> Type? ResolveTypeBySimpleName(string simpleTypeName); } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/CustomTypeProviders/IDynamicLinqCustomTypeProvider.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
312
```smalltalk namespace System.Linq.Dynamic.Core.CustomTypeProviders; /// <summary> /// Indicates to Dynamic Linq to consider the Type as a valid dynamic linq type. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.Enum, AllowMultiple = false, Inherited = false)] public sealed class DynamicLinqTypeAttribute : Attribute { } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/CustomTypeProviders/DynamicLinqTypeAttribute.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
78
```smalltalk using System.Collections.Generic; using System.Linq.Dynamic.Core.Validation; using System.Reflection; using System.Runtime.CompilerServices; namespace System.Linq.Dynamic.Core.CustomTypeProviders; /// <summary> /// The default implementation for <see cref="DefaultDynamicLinqCustomTypeProvider"/>. /// /// Scans the current AppDomain for all types marked with <see cref="DynamicLinqTypeAttribute"/>, and adds them as custom Dynamic Link types. /// /// Also provides functionality to resolve a Type in the current Application Domain. /// /// This class is used as default for full .NET Framework and .NET Core App 2.x and higher. /// </summary> public class DefaultDynamicLinqCustomTypeProvider : AbstractDynamicLinqCustomTypeProvider, IDynamicLinkCustomTypeProvider { private readonly IAssemblyHelper _assemblyHelper; private readonly bool _cacheCustomTypes; private HashSet<Type>? _cachedCustomTypes; private Dictionary<Type, List<MethodInfo>>? _cachedExtensionMethods; /// <summary> /// Initializes a new instance of the <see cref="DefaultDynamicLinqCustomTypeProvider"/> class. /// Backwards compatibility for issue path_to_url /// </summary> /// <param name="cacheCustomTypes">Defines whether to cache the CustomTypes (including extension methods) which are found in the Application Domain. Default set to 'true'.</param> [Obsolete("Please use the DefaultDynamicLinqCustomTypeProvider(ParsingConfig config, bool cacheCustomTypes = true) constructor.")] public DefaultDynamicLinqCustomTypeProvider(bool cacheCustomTypes = true) : this(ParsingConfig.Default, cacheCustomTypes) { } /// <summary> /// Initializes a new instance of the <see cref="DefaultDynamicLinqCustomTypeProvider"/> class. /// </summary> /// <param name="config">The parsing configuration.</param> /// <param name="cacheCustomTypes">Defines whether to cache the CustomTypes (including extension methods) which are found in the Application Domain. Default set to 'true'.</param> public DefaultDynamicLinqCustomTypeProvider(ParsingConfig config, bool cacheCustomTypes = true) { _assemblyHelper = new DefaultAssemblyHelper(Check.NotNull(config)); _cacheCustomTypes = cacheCustomTypes; } /// <inheritdoc cref="IDynamicLinqCustomTypeProvider.GetCustomTypes"/> public virtual HashSet<Type> GetCustomTypes() { if (_cacheCustomTypes) { if (_cachedCustomTypes == null) { _cachedCustomTypes = GetCustomTypesInternal(); } return _cachedCustomTypes; } return GetCustomTypesInternal(); } /// <inheritdoc cref="IDynamicLinqCustomTypeProvider.GetExtensionMethods"/> public Dictionary<Type, List<MethodInfo>> GetExtensionMethods() { if (_cacheCustomTypes) { if (_cachedExtensionMethods == null) { _cachedExtensionMethods = GetExtensionMethodsInternal(); } return _cachedExtensionMethods; } return GetExtensionMethodsInternal(); } /// <inheritdoc cref="IDynamicLinqCustomTypeProvider.ResolveType"/> public Type? ResolveType(string typeName) { Check.NotEmpty(typeName); IEnumerable<Assembly> assemblies = _assemblyHelper.GetAssemblies(); return ResolveType(assemblies, typeName); } /// <inheritdoc cref="IDynamicLinqCustomTypeProvider.ResolveTypeBySimpleName"/> public Type? ResolveTypeBySimpleName(string simpleTypeName) { Check.NotEmpty(simpleTypeName); IEnumerable<Assembly> assemblies = _assemblyHelper.GetAssemblies(); return ResolveTypeBySimpleName(assemblies, simpleTypeName); } private HashSet<Type> GetCustomTypesInternal() { IEnumerable<Assembly> assemblies = _assemblyHelper.GetAssemblies(); return new HashSet<Type>(FindTypesMarkedWithDynamicLinqTypeAttribute(assemblies)); } private Dictionary<Type, List<MethodInfo>> GetExtensionMethodsInternal() { var types = GetCustomTypes(); var list = new List<Tuple<Type, MethodInfo>>(); foreach (var type in types) { var extensionMethods = type .GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) .Where(x => x.IsDefined(typeof(ExtensionAttribute), false)) .ToList(); extensionMethods.ForEach(x => list.Add(new Tuple<Type, MethodInfo>(x.GetParameters()[0].ParameterType, x))); } return list.GroupBy(x => x.Item1, tuple => tuple.Item2).ToDictionary(key => key.Key, methods => methods.ToList()); } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/CustomTypeProviders/DefaultDynamicLinqCustomTypeProvider.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
957
```smalltalk using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq.Dynamic.Core.Validation; namespace System.Linq.Dynamic.Core.Extensions; [SuppressMessage("ReSharper", "PossibleMultipleEnumeration")] internal static class LinqExtensions { public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> sequence) { Check.NotNull(sequence); return sequence.Where(e => e != null)!; } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Extensions/LinqExtensions.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
82
```smalltalk using System.Linq.Dynamic.Core.Tokenizer; namespace System.Linq.Dynamic.Core.Extensions; internal static class TokenIdExtensions { internal static bool IsEqualityOperator(this TokenId tokenId) { return tokenId is TokenId.Equal or TokenId.DoubleEqual or TokenId.ExclamationEqual or TokenId.LessGreater; } internal static bool IsComparisonOperator(this TokenId tokenId) { return tokenId is TokenId.Equal or TokenId.DoubleEqual or TokenId.ExclamationEqual or TokenId.LessGreater or TokenId.GreaterThan or TokenId.GreaterThanEqual or TokenId.LessThan or TokenId.LessThanEqual; } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Extensions/TokenIdExtensions.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
133
```smalltalk using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq.Dynamic.Core.Extensions; using System.Linq.Dynamic.Core.Validation; using System.Reflection; namespace System.Linq.Dynamic.Core.CustomTypeProviders; /// <summary> /// The abstract DynamicLinqCustomTypeProvider which is used by the DefaultDynamicLinqCustomTypeProvider and can be used by a custom TypeProvider like in .NET Core. /// </summary> [SuppressMessage("ReSharper", "PossibleMultipleEnumeration")] public abstract class AbstractDynamicLinqCustomTypeProvider { /// <summary> /// Finds the unique types marked with DynamicLinqTypeAttribute. /// </summary> /// <param name="assemblies">The assemblies to process.</param> /// <returns><see cref="IEnumerable{Type}" /></returns> protected IEnumerable<Type> FindTypesMarkedWithDynamicLinqTypeAttribute(IEnumerable<Assembly> assemblies) { Check.NotNull(assemblies); #if !NET35 assemblies = assemblies.Where(a => !a.IsDynamic); #endif return GetAssemblyTypesWithDynamicLinqTypeAttribute(assemblies).Distinct().ToArray(); } /// <summary> /// Resolve any type which is registered in the current application domain. /// </summary> /// <param name="assemblies">The assemblies to inspect.</param> /// <param name="typeName">The typename to resolve.</param> /// <returns>A resolved <see cref="Type"/> or null when not found.</returns> protected Type? ResolveType(IEnumerable<Assembly> assemblies, string typeName) { Check.NotNull(assemblies); Check.NotEmpty(typeName); foreach (var assembly in assemblies) { var resolvedType = assembly.GetType(typeName, false, true); if (resolvedType != null) { return resolvedType; } } return null; } /// <summary> /// Resolve a type by the simple name which is registered in the current application domain. /// </summary> /// <param name="assemblies">The assemblies to inspect.</param> /// <param name="simpleTypeName">The simple typename to resolve.</param> /// <returns>A resolved <see cref="Type"/> or null when not found.</returns> protected Type? ResolveTypeBySimpleName(IEnumerable<Assembly> assemblies, string simpleTypeName) { Check.NotNull(assemblies); Check.NotEmpty(simpleTypeName); foreach (var assembly in assemblies) { var fullNames = assembly.GetTypes().Select(t => t.FullName!).Distinct(); var firstMatchingFullname = fullNames.FirstOrDefault(fn => fn.EndsWith($".{simpleTypeName}")); if (firstMatchingFullname != null) { var resolvedType = assembly.GetType(firstMatchingFullname, false, true); if (resolvedType != null) { return resolvedType; } } } return null; } #if (UAP10_0 || NETSTANDARD) /// <summary> /// Gets the assembly types annotated with <see cref="DynamicLinqTypeAttribute"/> in an Exception friendly way. /// </summary> /// <param name="assemblies">The assemblies to process.</param> /// <returns>Array of <see cref="Type" /></returns> protected Type[] GetAssemblyTypesWithDynamicLinqTypeAttribute(IEnumerable<Assembly> assemblies) { Check.NotNull(assemblies); var dynamicLinqTypes = new List<Type>(); foreach (var assembly in assemblies) { Type[] definedTypes; try { definedTypes = assembly.GetExportedTypes(); } catch { // Ignore all other exceptions definedTypes = Type.EmptyTypes; } foreach (var definedType in definedTypes) { try { if (definedType.GetTypeInfo().IsDefined(typeof(DynamicLinqTypeAttribute), false)) { dynamicLinqTypes.Add(definedType); } } catch { // Ignore } } } return dynamicLinqTypes.Distinct().ToArray(); } #else /// <summary> /// Gets the assembly types annotated with <see cref="DynamicLinqTypeAttribute"/> in an Exception friendly way. /// </summary> /// <param name="assemblies">The assemblies to process.</param> /// <returns>Array of <see cref="Type" /></returns> protected Type[] GetAssemblyTypesWithDynamicLinqTypeAttribute(IEnumerable<Assembly> assemblies) { Check.NotNull(assemblies); var dynamicLinqTypes = new List<Type>(); #if !NET5_0_OR_GREATER assemblies = assemblies.Where(a => !a.GlobalAssemblyCache).ToArray(); // Skip System DLL's #endif foreach (var assembly in assemblies) { Type[] definedTypes; try { definedTypes = assembly.GetTypes(); } catch (ReflectionTypeLoadException reflectionTypeLoadException) { definedTypes = reflectionTypeLoadException.Types.WhereNotNull().ToArray(); } catch { // Ignore all other exceptions definedTypes = Type.EmptyTypes; } foreach (var definedType in definedTypes) { try { if (definedType.IsDefined(typeof(DynamicLinqTypeAttribute), false)) { dynamicLinqTypes.Add(definedType); } } catch { // Ignore } } } return dynamicLinqTypes.Distinct().ToArray(); } #endif } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/CustomTypeProviders/AbstractDynamicLinqCustomTypeProvider.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
1,158
```smalltalk namespace System.Linq.Dynamic.Core.Tokenizer { /// <summary> /// Token /// </summary> public struct Token { /// <summary> /// The TokenId. /// </summary> public TokenId Id { get; set; } /// <summary> /// The Original TokenId. /// </summary> public TokenId OriginalId { get; set; } /// <summary> /// The text. /// </summary> public string Text { get; set; } /// <summary> /// The position. /// </summary> public int Pos { get; set; } } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Tokenizer/Token.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
140
```smalltalk #pragma warning disable CS1591 namespace System.Linq.Dynamic.Core.Tokenizer; /// <summary> /// TokenId which defines the text which is parsed. /// </summary> public enum TokenId { Unknown, End, Identifier, StringLiteral, IntegerLiteral, RealLiteral, // ! Exclamation, // % (Modulus Operator) Percent, // & Ampersand, // ( OpenParen, // ) CloseParen, // { OpenCurlyParen, // } CloseCurlyParen, // * Asterisk, // + Plus, // , Comma, // - Minus, // . Dot, // / Slash, // : Colon, // < LessThan, // = Equal, // > GreaterThan, // ? Question, // [ OpenBracket, // ] CloseBracket, // | Bar, // != ExclamationEqual, // && DoubleAmpersand, // <= LessThanEqual, // <> LessGreater, // == DoubleEqual, // >= GreaterThanEqual, // || DoubleBar, // >> (Shift Operator) DoubleGreaterThan, // << (Shift Operator) DoubleLessThan, // ?? NullCoalescing, // => Lambda, // ?. NullPropagation } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Tokenizer/TokenId.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
316
```smalltalk namespace System.Linq.Dynamic.Core.Config; /// <summary> /// Defines the types of string literal parsing that can be performed. /// </summary> public enum StringLiteralParsingType : byte { /// <summary> /// Represents the default string literal parsing type. Double quotes should be escaped using the default escape character (a \). /// To check if a Value equals a double quote, use this c# code: /// <code> /// var expression = "Value == \"\\\"\""; /// </code> /// </summary> Default = 0, /// <summary> /// Represents a string literal parsing type where a double quote should be escaped by an extra double quote ("). /// To check if a Value equals a double quote, use this c# code: /// <code> /// var expression = "Value == \"\"\"\""; /// </code> /// </summary> EscapeDoubleQuoteByTwoDoubleQuotes = 1 } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Config/StringLiteralParsingType.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
204
```smalltalk using System.Globalization; #if !(SILVERLIGHT || WINDOWS_APP || UAP10_0 || NETSTANDARD || PORTABLE || WPSL) using System.Runtime.Serialization; #endif namespace System.Linq.Dynamic.Core.Exceptions { /// <summary> /// Represents errors that occur while parsing dynamic linq string expressions. /// </summary> #if !(SILVERLIGHT || UAP10_0 || NETSTANDARD || PORTABLE || WPSL || NETSTANDARD2_0) [Serializable] #endif public sealed class ParseException : Exception { /// <summary> /// The location in the parsed string that produced the <see cref="ParseException"/>. /// </summary> public int Position { get; } /// <summary> /// Initializes a new instance of the <see cref="ParseException"/> class with a specified error message and position. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="position">The location in the parsed string that produced the <see cref="ParseException"/></param> /// <param name="innerException">The exception that is the cause of the current exception, or a null reference if no inner exception is specified.</param> public ParseException(string message, int position, Exception? innerException = null) : base(message, innerException) { Position = position; } /// <summary> /// Creates and returns a string representation of the current exception. /// </summary> /// <returns>A string representation of the current exception.</returns> public override string ToString() { var text = string.Format(CultureInfo.CurrentCulture, Res.ParseExceptionFormat, Message, Position); if (InnerException != null) { text = $"{text} ---> {InnerException}{Environment.NewLine} --- End of inner exception stack trace ---"; } if (StackTrace != null) { text = $"{text}{Environment.NewLine}{StackTrace}"; } return text; } #if !(SILVERLIGHT || UAP10_0 || NETSTANDARD || PORTABLE || WPSL || NETSTANDARD2_0) private ParseException(SerializationInfo info, StreamingContext context) : base(info, context) { Position = (int)info.GetValue("position", typeof(int)); } /// <summary> /// When overridden in a derived class, sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <PermissionSet> /// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Read="*AllFiles*" PathDiscovery="*AllFiles*" /> /// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="SerializationFormatter" /> /// </PermissionSet> public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("position", Position); } #endif } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Exceptions/ParseException.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
776
```smalltalk using System.Collections.Generic; using System.Globalization; using System.Linq.Dynamic.Core.Exceptions; namespace System.Linq.Dynamic.Core.Tokenizer; /// <summary> /// TextParser which can be used to parse a text into tokens. /// </summary> public class TextParser { private const char DefaultNumberDecimalSeparator = '.'; private static readonly char[] EscapeCharacters = { '\\', 'a', 'b', 'f', 'n', 'r', 't', 'v' }; // These aliases are supposed to simply the where clause and make it more human readable private static readonly Dictionary<string, TokenId> PredefinedOperatorAliases = new(StringComparer.OrdinalIgnoreCase) { { "eq", TokenId.Equal }, { "equal", TokenId.Equal }, { "ne", TokenId.ExclamationEqual }, { "notequal", TokenId.ExclamationEqual }, { "neq", TokenId.ExclamationEqual }, { "lt", TokenId.LessThan }, { "LessThan", TokenId.LessThan }, { "le", TokenId.LessThanEqual }, { "LessThanEqual", TokenId.LessThanEqual }, { "gt", TokenId.GreaterThan }, { "GreaterThan", TokenId.GreaterThan }, { "ge", TokenId.GreaterThanEqual }, { "GreaterThanEqual", TokenId.GreaterThanEqual }, { "and", TokenId.DoubleAmpersand }, { "AndAlso", TokenId.DoubleAmpersand }, { "or", TokenId.DoubleBar }, { "OrElse", TokenId.DoubleBar }, { "not", TokenId.Exclamation }, { "mod", TokenId.Percent } }; private readonly char _numberDecimalSeparator; private readonly string _text; private readonly int _textLen; private readonly ParsingConfig _parsingConfig; private int _textPos; private char _ch; /// <summary> /// The current parsed <see cref="Token"/>. /// </summary> public Token CurrentToken; /// <summary> /// Constructor for TextParser /// </summary> /// <param name="config"></param> /// <param name="text"></param> public TextParser(ParsingConfig config, string text) { _parsingConfig = config; _numberDecimalSeparator = config.NumberParseCulture?.NumberFormat.NumberDecimalSeparator[0] ?? DefaultNumberDecimalSeparator; _text = text; _textLen = _text.Length; SetTextPos(0); NextToken(); } /// <summary> /// This method is used to clone the current <see cref="TextParser"/>. /// </summary> /// <returns>Cloned <see cref="TextParser"/></returns> public TextParser Clone() { var clone = new TextParser(_parsingConfig, _text); clone.SetTextPos(_textPos); return clone; } /// <summary> /// Peek the next character. /// </summary> /// <returns>The next character, or \0 if end of string.</returns> public char PeekNextChar() { return _textPos + 1 < _textLen ? _text[_textPos + 1] : '\0'; } /// <summary> /// Go to the next token. /// </summary> public void NextToken() { while (char.IsWhiteSpace(_ch)) { NextChar(); } TokenId tokenId; var tokenPos = _textPos; switch (_ch) { case '!': NextChar(); if (_ch == '=') { NextChar(); tokenId = TokenId.ExclamationEqual; } else { tokenId = TokenId.Exclamation; } break; case '%': NextChar(); tokenId = TokenId.Percent; break; case '&': NextChar(); if (_ch == '&') { NextChar(); tokenId = TokenId.DoubleAmpersand; } else { tokenId = TokenId.Ampersand; } break; case '(': NextChar(); tokenId = TokenId.OpenParen; break; case ')': NextChar(); tokenId = TokenId.CloseParen; break; case '{': NextChar(); tokenId = TokenId.OpenCurlyParen; break; case '}': NextChar(); tokenId = TokenId.CloseCurlyParen; break; case '*': NextChar(); tokenId = TokenId.Asterisk; break; case '+': NextChar(); tokenId = TokenId.Plus; break; case ',': NextChar(); tokenId = TokenId.Comma; break; case '-': NextChar(); tokenId = TokenId.Minus; break; case '.': NextChar(); tokenId = TokenId.Dot; break; case '/': NextChar(); tokenId = TokenId.Slash; break; case ':': NextChar(); tokenId = TokenId.Colon; break; case '<': NextChar(); if (_ch == '=') { NextChar(); tokenId = TokenId.LessThanEqual; } else if (_ch == '>') { NextChar(); tokenId = TokenId.LessGreater; } else if (_ch == '<') { NextChar(); tokenId = TokenId.DoubleLessThan; } else { tokenId = TokenId.LessThan; } break; case '=': NextChar(); if (_ch == '=') { NextChar(); tokenId = TokenId.DoubleEqual; } else if (_ch == '>') { NextChar(); tokenId = TokenId.Lambda; } else { tokenId = TokenId.Equal; } break; case '>': NextChar(); if (_ch == '=') { NextChar(); tokenId = TokenId.GreaterThanEqual; } else if (_ch == '>') { NextChar(); tokenId = TokenId.DoubleGreaterThan; } else { tokenId = TokenId.GreaterThan; } break; case '?': NextChar(); if (_ch == '?') { NextChar(); tokenId = TokenId.NullCoalescing; } else if (_ch == '.') { NextChar(); tokenId = TokenId.NullPropagation; } else { tokenId = TokenId.Question; } break; case '[': NextChar(); tokenId = TokenId.OpenBracket; break; case ']': NextChar(); tokenId = TokenId.CloseBracket; break; case '|': NextChar(); if (_ch == '|') { NextChar(); tokenId = TokenId.DoubleBar; } else { tokenId = TokenId.Bar; } break; case '"': case '\'': var quoteIsBalanced = false; var quote = _ch; NextChar(); while (_textPos < _textLen && _ch != quote) { var nextChar = PeekNextChar(); if (_ch == '\\') { if (EscapeCharacters.Contains(nextChar)) { NextChar(); } if (nextChar == '"') { NextChar(); } } NextChar(); if (_ch == quote) { quoteIsBalanced = !quoteIsBalanced; } } if (_textPos == _textLen && !quoteIsBalanced) { throw ParseError(_textPos, Res.UnterminatedStringLiteral); } NextChar(); tokenId = TokenId.StringLiteral; break; default: if (char.IsLetter(_ch) || _ch is '@' or '_' or '$' or '^' or '~') { do { NextChar(); } while (char.IsLetterOrDigit(_ch) || _ch == '_'); tokenId = TokenId.Identifier; break; } if (char.IsDigit(_ch)) { tokenId = TokenId.IntegerLiteral; do { NextChar(); } while (char.IsDigit(_ch)); bool binaryInteger = false; if (_ch is 'B' or 'b') { NextChar(); ValidateBinaryChar(); do { NextChar(); } while (IsZeroOrOne(_ch)); binaryInteger = true; } if (binaryInteger) { break; } var isHexInteger = false; if (_ch is 'X' or 'x') { NextChar(); ValidateHexChar(); do { NextChar(); } while (IsHexChar(_ch)); isHexInteger = true; } if (_ch is 'U' or 'L') { NextChar(); if (_ch == 'L') { if (_text[_textPos - 1] == 'U') { NextChar(); } else { throw ParseError(_textPos, Res.InvalidIntegerQualifier, _text.Substring(_textPos - 1, 2)); } } ValidateExpression(); break; } if (isHexInteger) { break; } if (_ch == _numberDecimalSeparator) { tokenId = TokenId.RealLiteral; NextChar(); ValidateDigit(); do { NextChar(); } while (char.IsDigit(_ch)); } if (_ch is 'E' or 'e') { tokenId = TokenId.RealLiteral; NextChar(); if (_ch is '+' or '-') { NextChar(); } ValidateDigit(); do { NextChar(); } while (char.IsDigit(_ch)); } if (_ch is 'F' or 'f') { NextChar(); } if (_ch is 'D' or 'd') { NextChar(); } if (_ch is 'M' or 'm') { NextChar(); } break; } if (_textPos == _textLen) { tokenId = TokenId.End; break; } throw ParseError(_textPos, Res.InvalidCharacter, _ch); } CurrentToken.Pos = tokenPos; CurrentToken.Text = _text.Substring(tokenPos, _textPos - tokenPos); CurrentToken.OriginalId = tokenId; CurrentToken.Id = GetAliasedTokenId(tokenId, CurrentToken.Text); } /// <summary> /// Check if the current token is the specified <see cref="TokenId"/>. /// </summary> /// <param name="tokenId">The tokenId to check.</param> /// <param name="errorMessage">The (optional) error message.</param> public void ValidateToken(TokenId tokenId, string? errorMessage = null) { if (CurrentToken.Id != tokenId) { throw ParseError(errorMessage ?? Res.SyntaxError); } } private void SetTextPos(int pos) { _textPos = pos; _ch = _textPos < _textLen ? _text[_textPos] : '\0'; } private void NextChar() { if (_textPos < _textLen) { _textPos++; } _ch = _textPos < _textLen ? _text[_textPos] : '\0'; } private void ValidateExpression() { if (char.IsLetterOrDigit(_ch)) { throw ParseError(_textPos, Res.ExpressionExpected); } } private void ValidateDigit() { if (!char.IsDigit(_ch)) { throw ParseError(_textPos, Res.DigitExpected); } } private void ValidateHexChar() { if (!IsHexChar(_ch)) { throw ParseError(_textPos, Res.HexCharExpected); } } private void ValidateBinaryChar() { if (!IsZeroOrOne(_ch)) { throw ParseError(_textPos, Res.BinaryCharExpected); } } private Exception ParseError(string format, params object[] args) { return ParseError(CurrentToken.Pos, format, args); } private static Exception ParseError(int pos, string format, params object[] args) { return new ParseException(string.Format(CultureInfo.CurrentCulture, format, args), pos); } private static TokenId GetAliasedTokenId(TokenId tokenId, string alias) { return tokenId == TokenId.Identifier && PredefinedOperatorAliases.TryGetValue(alias, out TokenId id) ? id : tokenId; } private static bool IsHexChar(char c) { if (char.IsDigit(c)) { return true; } if (c <= '\x007f') { c |= (char)0x20; return c is >= 'a' and <= 'f'; } return false; } private static bool IsZeroOrOne(char c) { return c is '0' or '1'; } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Tokenizer/TextParser.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
2,853
```smalltalk //your_sha256_hash-------------- // <auto-generated> // This code was generated by path_to_url // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //your_sha256_hash-------------- namespace AnyOfTypes { internal enum AnyOfType { Undefined = 0, First, Second, Third, Fourth, Fifth, Sixth, Seventh, Eighth, Ninth, Tenth } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/AnyOfTypes/AnyOfTypes.g.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
103
```smalltalk //your_sha256_hash-------------- // <auto-generated> // This code was generated by path_to_url // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //your_sha256_hash-------------- using System; using System.Diagnostics; using System.Collections.Generic; namespace AnyOfTypes { [DebuggerDisplay("{_thisType}, AnyOfType = {_currentType}; Type = {_currentValueType?.Name}; Value = '{ToString()}'")] internal struct AnyOf<TFirst, TSecond> { private readonly string _thisType => $"AnyOf<{typeof(TFirst).Name}, {typeof(TSecond).Name}>"; private readonly int _numberOfTypes; private readonly object _currentValue; private readonly Type _currentValueType; private readonly AnyOfType _currentType; private readonly TFirst _first; private readonly TSecond _second; public readonly AnyOfType[] AnyOfTypes => new[] { AnyOfType.First, AnyOfType.Second }; public readonly Type[] Types => new[] { typeof(TFirst), typeof(TSecond) }; public bool IsUndefined => _currentType == AnyOfType.Undefined; public bool IsFirst => _currentType == AnyOfType.First; public bool IsSecond => _currentType == AnyOfType.Second; public static implicit operator AnyOf<TFirst, TSecond>(TFirst value) => new AnyOf<TFirst, TSecond>(value); public static implicit operator TFirst(AnyOf<TFirst, TSecond> @this) => @this.First; public AnyOf(TFirst value) { _numberOfTypes = 2; _currentType = AnyOfType.First; _currentValue = value; _currentValueType = typeof(TFirst); _first = value; _second = default; } public TFirst First { get { Validate(AnyOfType.First); return _first; } } public static implicit operator AnyOf<TFirst, TSecond>(TSecond value) => new AnyOf<TFirst, TSecond>(value); public static implicit operator TSecond(AnyOf<TFirst, TSecond> @this) => @this.Second; public AnyOf(TSecond value) { _numberOfTypes = 2; _currentType = AnyOfType.Second; _currentValue = value; _currentValueType = typeof(TSecond); _second = value; _first = default; } public TSecond Second { get { Validate(AnyOfType.Second); return _second; } } private void Validate(AnyOfType desiredType) { if (desiredType != _currentType) { throw new InvalidOperationException($"Attempting to get {desiredType} when {_currentType} is set"); } } public AnyOfType CurrentType { get { return _currentType; } } public object CurrentValue { get { return _currentValue; } } public Type CurrentValueType { get { return _currentValueType; } } public override int GetHashCode() { var fields = new object[] { _numberOfTypes, _currentValue, _currentType, _first, _second, typeof(TFirst), typeof(TSecond), }; return HashCodeCalculator.GetHashCode(fields); } private bool Equals(AnyOf<TFirst, TSecond> other) { return _currentType == other._currentType && _numberOfTypes == other._numberOfTypes && EqualityComparer<object>.Default.Equals(_currentValue, other._currentValue) && EqualityComparer<TFirst>.Default.Equals(_first, other._first) && EqualityComparer<TSecond>.Default.Equals(_second, other._second); } public static bool operator ==(AnyOf<TFirst, TSecond> obj1, AnyOf<TFirst, TSecond> obj2) { return obj1.Equals(obj2); } public static bool operator !=(AnyOf<TFirst, TSecond> obj1, AnyOf<TFirst, TSecond> obj2) { return !obj1.Equals(obj2); } public override bool Equals(object obj) { return obj is AnyOf<TFirst, TSecond> o && Equals(o); } public override string ToString() { return IsUndefined ? null : $"{_currentValue}"; } } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/AnyOfTypes/AnyOf_2.g.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
962
```smalltalk namespace System.Linq.Dynamic.Core.Util; internal static class RuntimeInformationUtils { public static bool IsBlazorWASM; static RuntimeInformationUtils() { #if NET35 || NET40 || NET45 || NET452 || NET46 || UAP10_0 IsBlazorWASM = false; #else IsBlazorWASM = // Used for Blazor WebAssembly .NET Core 3.x / .NET Standard 2.x Type.GetType("Mono.Runtime") != null || // Use for Blazor WebAssembly .NET // See also path_to_url Runtime.InteropServices.RuntimeInformation.IsOSPlatform(Runtime.InteropServices.OSPlatform.Create("BROWSER")); #endif } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Util/RuntimeInformationUtils.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
148
```smalltalk //your_sha256_hash-------------- // <auto-generated> // This code was generated by path_to_url // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //your_sha256_hash-------------- using System.Collections.Generic; using System.Linq; namespace AnyOfTypes { // Code is based on path_to_url internal static class HashCodeCalculator { public static int GetHashCode(IEnumerable<object> hashFieldValues) { const int offset = unchecked((int)2166136261); const int prime = 16777619; static int HashCodeAggregator(int hashCode, object value) => value == null ? (hashCode ^ 0) * prime : (hashCode ^ value.GetHashCode()) * prime; return hashFieldValues.Aggregate(offset, HashCodeAggregator); } } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/AnyOfTypes/HashCodeCalculator.g.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
191
```smalltalk namespace System.Linq.Dynamic.Core.Util { internal interface IDateTimeUtils { DateTime UtcNow { get; } } internal class DateTimeUtils : IDateTimeUtils { public DateTime UtcNow => DateTime.UtcNow; } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Util/DateTimeUtils.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
54
```smalltalk using System.Linq.Dynamic.Core.Validation; namespace System.Linq.Dynamic.Core.Util; internal static class TaskUtils { public static void Run(Action action) { Check.NotNull(action); #if NET35 || NET40 System.Threading.ThreadPool.QueueUserWorkItem(_ => action.Invoke()); #else System.Threading.Tasks.Task.Run(action); #endif } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Util/TaskUtils.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
73
```smalltalk using System.Collections.Generic; using System.Linq.Dynamic.Core.Parser; using System.Linq.Expressions; using System.Reflection; namespace System.Linq.Dynamic.Core.Util; internal static class QueryableMethodFinder { public static MethodInfo GetGenericMethod(string name) { return typeof(Queryable).GetTypeInfo().GetDeclaredMethods(name).Single(mi => mi.IsGenericMethod); } public static MethodInfo GetMethod(string name, Type argumentType, Type returnType, int parameterCount = 0, Func<MethodInfo, bool>? predicate = null) => GetMethod(name, returnType, parameterCount, mi => mi.ToString().Contains(argumentType.ToString()) && (predicate == null || predicate(mi))); public static MethodInfo GetMethod(string name, Type returnType, int parameterCount = 0, Func<MethodInfo, bool>? predicate = null) { var returnTypes = new List<Type> { returnType }; if (!TypeHelper.IsNullableType(returnType)) { returnTypes.Add(TypeHelper.GetNullableType(returnType)); } return GetMethod(name, parameterCount, mi => returnTypes.Contains(mi.ReturnType) && (predicate == null || predicate(mi))); } public static MethodInfo GetMethodWithExpressionParameter(string name) => GetMethod(name, 1, mi => mi.GetParameters().Length == 2 && mi.GetParameters()[1].ParameterType.GetTypeInfo().IsGenericType && mi.GetParameters()[1].ParameterType.GetGenericTypeDefinition() == typeof(Expression<>) && mi.GetParameters()[1].ParameterType.GetGenericArguments()[0].GetTypeInfo().IsGenericType && mi.GetParameters()[1].ParameterType.GetGenericArguments()[0].GetGenericTypeDefinition() == typeof(Func<,>) ); public static MethodInfo GetMethodWithIntParameter(string name) => GetMethod(name, 1, mi => mi.GetParameters().Length == 2 && mi.GetParameters()[1].ParameterType == typeof(int) ); public static MethodInfo GetMethod(string name, int parameterCount = 0, Func<MethodInfo, bool>? predicate = null) { try { return typeof(Queryable).GetTypeInfo().GetDeclaredMethods(name).First(mi => mi.GetParameters().Length == parameterCount + 1 && (predicate == null || predicate(mi))); } catch (Exception ex) { throw new Exception("Specific method not found: " + name, ex); } } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Util/QueryableMethodFinder.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
502
```smalltalk namespace System.Linq.Dynamic.Core.Util.Cache; internal static class SlidingCacheConstants { // Default cleanup frequency public static readonly TimeSpan DefaultCleanupFrequency = TimeSpan.FromMinutes(10); // Default Time-To-Live public static readonly TimeSpan DefaultTimeToLive = TimeSpan.FromMinutes(10); } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Util/Cache/SlidingCacheConstants.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
64
```smalltalk using System.Linq.Dynamic.Core.Validation; using System.Linq.Expressions; namespace System.Linq.Dynamic.Core.Util; /// <summary> /// Renames a single (Typed)ParameterExpression in an Expression. /// </summary> /// <seealso cref="ExpressionVisitor" /> internal class ParameterExpressionRenamer : ExpressionVisitor { private readonly string _newName; private readonly string _oldName; private ParameterExpression? _parameterExpression; /// <summary> /// Initializes a new instance of the <see cref="ParameterExpressionRenamer"/> class. /// </summary> /// <param name="newName">The new name (the oldName is assumed to be "").</param> public ParameterExpressionRenamer(string newName) : this(string.Empty, newName) { } /// <summary> /// Initializes a new instance of the <see cref="ParameterExpressionRenamer"/> class. /// </summary> /// <param name="oldName">The old name.</param> /// <param name="newName">The new name.</param> public ParameterExpressionRenamer(string oldName, string newName) { _oldName = Check.NotNull(oldName); _newName = Check.NotEmpty(newName); } /// <summary> /// Renames a single (Typed)ParameterExpression from specified expression. /// </summary> /// <param name="expression">The expression.</param> /// <param name="parameterExpression">The new generated (Typed)ParameterExpression.</param> /// <returns>Renamed Expression</returns> public Expression Rename(Expression expression, out ParameterExpression? parameterExpression) { var visitedExpression = Visit(expression); parameterExpression = _parameterExpression; return visitedExpression; } /// <inheritdoc cref="ExpressionVisitor.VisitParameter"/> protected override Expression VisitParameter(ParameterExpression node) { if (string.Equals(_oldName, node.Name, StringComparison.Ordinal)) { if (_parameterExpression == null) { _parameterExpression = ParameterExpressionHelper.CreateParameterExpression(node.Type, _newName); } return _parameterExpression; // throw new InvalidOperationException($"The {nameof(ParameterExpressionRenamer)} can only rename 1 (Typed)ParameterExpression in an Expression."); } return node; } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Util/ParameterExpressionRenamer.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
479
```smalltalk namespace System.Linq.Dynamic.Core.Util.Cache; /// <summary> /// Cache Configuration Options /// </summary> public class CacheConfig { /// <summary> /// Sets a Time-To-Live (TTL) for items in the constant expression cache to prevent uncontrolled growth. /// Items not accessed within this TTL will be expired, allowing garbage collection to reclaim the memory. /// Default is 10 minutes. /// </summary> public TimeSpan TimeToLive { get; set; } = SlidingCacheConstants.DefaultTimeToLive; /// <summary> /// Configures the minimum number of items required in the constant expression cache before triggering cleanup. /// This prevents frequent cleanups, especially in caches with few items. /// A default value of null implies that cleanup is always allowed to run, helping in timely removal of unused cache items. /// </summary> public int? MinItemsTrigger { get; set; } /// <summary> /// Sets the frequency for running the cleanup process in the Constant Expression cache. /// By default, cleanup occurs every 10 minutes. /// </summary> public TimeSpan CleanupFrequency { get; set; } = SlidingCacheConstants.DefaultCleanupFrequency; /// <summary> /// Enables returning expired cache items in scenarios where cleanup, running on a separate thread, /// has not yet removed them. This allows for the retrieval of an expired object without needing to /// clear and recreate it if a request is made concurrently with cleanup. Particularly useful /// when cached items are deterministic, ensuring consistent results even from expired entries. /// Default true; /// </summary> public bool ReturnExpiredItems { get; set; } = true; } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Util/Cache/CacheConfig.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
362
```smalltalk namespace System.Linq.Dynamic.Core.Util.Cache; internal struct CacheEntry<TValue> where TValue : notnull { public TValue Value { get; } public DateTime ExpirationTime { get; } public CacheEntry(TValue value, DateTime expirationTime) { Value = value; ExpirationTime = expirationTime; } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Util/Cache/CacheEntry.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
72
```smalltalk using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; using System.Linq.Dynamic.Core.Validation; using System.Threading; namespace System.Linq.Dynamic.Core.Util.Cache; internal class SlidingCache<TKey, TValue> where TKey : notnull where TValue : notnull { private readonly ConcurrentDictionary<TKey, CacheEntry<TValue>> _cache; private readonly TimeSpan _cleanupFrequency; private readonly IDateTimeUtils _dateTimeProvider; private readonly Action _deleteExpiredCachedItemsDelegate; private readonly long? _minCacheItemsBeforeCleanup; private readonly bool _returnExpiredItems; private DateTime _lastCleanupTime; private int _cleanupLocked = 0; /// <summary> /// Sliding Thread Safe Cache /// </summary> /// <param name="timeToLive">The length of time any object would survive before being removed</param> /// <param name="cleanupFrequency">Only look for expired objects over specific periods</param> /// <param name="minCacheItemsBeforeCleanup"> /// If defined, only allow the cleanup process after x number of cached items have /// been stored /// </param> /// <param name="dateTimeProvider"> /// Provides the Time for the Caching object. Default will be created if not supplied. Used /// for Testing classes /// </param> /// <param name="returnExpiredItems">If a request for an item happens to be expired, but is still /// in known, don't expire it and return it instead.</param> public SlidingCache( TimeSpan timeToLive, TimeSpan? cleanupFrequency = null, long? minCacheItemsBeforeCleanup = null, IDateTimeUtils? dateTimeProvider = null, bool returnExpiredItems = false) { _cache = new ConcurrentDictionary<TKey, CacheEntry<TValue>>(); TimeToLive = timeToLive; _minCacheItemsBeforeCleanup = minCacheItemsBeforeCleanup; _returnExpiredItems = returnExpiredItems; _cleanupFrequency = cleanupFrequency ?? SlidingCacheConstants.DefaultCleanupFrequency; _deleteExpiredCachedItemsDelegate = Cleanup; _dateTimeProvider = dateTimeProvider ?? new DateTimeUtils(); // To prevent a scan on first call, set the last Cleanup to the current Provider time _lastCleanupTime = _dateTimeProvider.UtcNow; } /// <summary> /// Sliding Thread Safe Cache /// </summary> /// <param name="cacheConfig">The <see cref="CacheConfig"/> to use.</param> /// <param name="dateTimeProvider"> /// Provides the Time for the Caching object. Default will be created if not supplied. Used /// for Testing classes /// </param> public SlidingCache(CacheConfig cacheConfig, IDateTimeUtils? dateTimeProvider = null) { Check.NotNull(cacheConfig); _cache = new ConcurrentDictionary<TKey, CacheEntry<TValue>>(); TimeToLive = cacheConfig.TimeToLive; _minCacheItemsBeforeCleanup = cacheConfig.MinItemsTrigger; _cleanupFrequency = cacheConfig.CleanupFrequency; _returnExpiredItems = cacheConfig.ReturnExpiredItems; _deleteExpiredCachedItemsDelegate = Cleanup; _dateTimeProvider = dateTimeProvider ?? new DateTimeUtils(); // To prevent a scan on first call, set the last Cleanup to the current Provider time _lastCleanupTime = _dateTimeProvider.UtcNow; } /// <summary> /// Cache TTL value /// </summary> public TimeSpan TimeToLive { get; } /// <summary> /// Provide the number of items in the cache /// </summary> public int Count => _cache.Count; /// <summary> /// Add or update the item in the cache, at the same time update the expiration time /// </summary> /// <param name="key"></param> /// <param name="value"></param> public void AddOrUpdate(TKey key, TValue value) { Check.NotNull(key); Check.NotNull(value); var expirationTime = _dateTimeProvider.UtcNow.Add(TimeToLive); _cache[key] = new CacheEntry<TValue>(value, expirationTime); CleanupIfNeeded(); } /// <summary> /// Attempt to get the value from the cache. This will extend the cache expiration time if the item is found /// </summary> /// <param name="key">Key</param> /// <param name="value">Value</param> /// <returns></returns> public bool TryGetValue(TKey key, [NotNullWhen(true)] out TValue? value) { Check.NotNull(key); try { if (_cache.TryGetValue(key, out var valueAndExpiration)) { // Permit expired returns will return the object even if was expired // this will prevent the need to re-create the object for the caller if (_returnExpiredItems || _dateTimeProvider.UtcNow <= valueAndExpiration.ExpirationTime) { value = valueAndExpiration.Value; var newExpire = _dateTimeProvider.UtcNow.Add(TimeToLive); _cache[key] = new CacheEntry<TValue>(value, newExpire); return true; } // Remove expired item _cache.TryRemove(key, out _); } } finally { // If permit expired returns are enabled, // we want to ensure the cache has a chance to get the value CleanupIfNeeded(); } value = default; return false; } public bool Remove(TKey key) { Check.NotNull(key); var removed = _cache.TryRemove(key, out _); CleanupIfNeeded(); return removed; } private void CleanupIfNeeded() { // Ensure this is only executing one at a time. if (Interlocked.CompareExchange(ref _cleanupLocked, 1, 0) != 0) { return; } try { if (_dateTimeProvider.UtcNow - _lastCleanupTime > _cleanupFrequency && (_minCacheItemsBeforeCleanup == null || _cache.Count >= _minCacheItemsBeforeCleanup) // Only cleanup if we have a minimum number of items in the cache. ) { // Set here, so we don't have re-entry due to large collection enumeration. _lastCleanupTime = _dateTimeProvider.UtcNow; TaskUtils.Run(_deleteExpiredCachedItemsDelegate); } } finally { // Release the lock _cleanupLocked = 0; } } private void Cleanup() { // Enumerate the key/value - safe per docs foreach (var keyValue in _cache) { if (_dateTimeProvider.UtcNow > keyValue.Value.ExpirationTime) { _cache.TryRemove(keyValue.Key, out _); } } } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Util/Cache/SlidingCache.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
1,447
```smalltalk using System.Linq.Expressions; using System.Reflection; namespace System.Linq.Dynamic.Core.Parser { /// <summary> /// ExpressionPromoter /// </summary> public class ExpressionPromoter : IExpressionPromoter { private readonly NumberParser _numberParser; private readonly ConstantExpressionHelper _constantExpressionHelper; /// <summary> /// Initializes a new instance of the <see cref="ExpressionPromoter"/> class. /// </summary> /// <param name="config">The ParsingConfig.</param> public ExpressionPromoter(ParsingConfig config) { _numberParser = new NumberParser(config); _constantExpressionHelper = ConstantExpressionHelperFactory.GetInstance(config); } /// <inheritdoc /> public virtual Expression? Promote(Expression expr, Type type, bool exact, bool convertExpr) { Type returnType; if (expr is LambdaExpression lambdaExpression) { returnType = lambdaExpression.GetReturnType(); } else { returnType = expr.Type; } if (returnType == type || type.IsGenericParameter) { return expr; } if (expr is ConstantExpression ce) { if (Constants.IsNull(ce)) { if (!type.GetTypeInfo().IsValueType || TypeHelper.IsNullableType(type)) { return Expression.Constant(null, type); } } else { if (_constantExpressionHelper.TryGetText(ce, out var text)) { Type target = TypeHelper.GetNonNullableType(type); object? value = null; #if !(UAP10_0 || NETSTANDARD) switch (Type.GetTypeCode(ce.Type)) { case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: value = _numberParser.ParseNumber(text, target); // Make sure an enum value stays an enum value if (target.IsEnum) { value = Enum.ToObject(target, value!); } break; case TypeCode.Double: if (target == typeof(decimal) || target == typeof(double)) { value = _numberParser.ParseNumber(text, target); } break; case TypeCode.String: TypeHelper.TryParseEnum(text, target, out value); break; } #else if (ce.Type == typeof(int) || ce.Type == typeof(uint) || ce.Type == typeof(long) || ce.Type == typeof(ulong)) { // If target is an enum value, just use the Value from the ConstantExpression if (target.GetTypeInfo().IsEnum) { value = Enum.ToObject(target, ce.Value); } else { value = _numberParser.ParseNumber(text!, target); } } else if (ce.Type == typeof(double)) { if (target == typeof(decimal) || target == typeof(double)) { value = _numberParser.ParseNumber(text, target); } } else if (ce.Type == typeof(string) && TypeHelper.TryParseEnum(text, target, out value)) { // Empty if } #endif if (value != null) { return Expression.Constant(value, type); } } } } if (TypeHelper.IsCompatibleWith(returnType, type)) { if (type == typeof(decimal) && TypeHelper.IsEnumType(expr.Type)) { return Expression.Convert(Expression.Convert(expr, Enum.GetUnderlyingType(expr.Type)), type); } if (type.GetTypeInfo().IsValueType || exact || expr.Type.GetTypeInfo().IsValueType && convertExpr) { return Expression.Convert(expr, type); } return expr; } return null; } } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/ExpressionPromoter.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
796
```smalltalk using System.Globalization; using System.Linq.Dynamic.Core.Exceptions; using System.Linq.Dynamic.Core.Validation; using System.Linq.Expressions; using System.Text.RegularExpressions; namespace System.Linq.Dynamic.Core.Parser { /// <summary> /// NumberParser /// </summary> public class NumberParser { private static readonly Regex RegexBinary32 = new("^[01]{1,32}$", RegexOptions.Compiled); private static readonly Regex RegexBinary64 = new("^[01]{1,64}$", RegexOptions.Compiled); private static readonly char[] Qualifiers = { 'U', 'u', 'L', 'l', 'F', 'f', 'D', 'd', 'M', 'm' }; private static readonly char[] QualifiersHex = { 'U', 'u', 'L', 'l' }; private static readonly string[] QualifiersReal = { "F", "f", "D", "d", "M", "m" }; private readonly ConstantExpressionHelper _constantExpressionHelper; private readonly CultureInfo _culture; /// <summary> /// Initializes a new instance of the <see cref="NumberParser"/> class. /// </summary> /// <param name="config">The ParsingConfig.</param> public NumberParser(ParsingConfig? config) { _culture = config?.NumberParseCulture ?? CultureInfo.InvariantCulture; _constantExpressionHelper = ConstantExpressionHelperFactory.GetInstance(config ?? ParsingConfig.Default); } /// <summary> /// Tries to parse the text into a IntegerLiteral ConstantExpression. /// </summary> /// <param name="tokenPosition">The current token position (needed for error reporting).</param> /// <param name="text">The text.</param> public Expression ParseIntegerLiteral(int tokenPosition, string text) { Check.NotEmpty(text, nameof(text)); var last = text[text.Length - 1]; var isNegative = text[0] == '-'; var isHexadecimal = text.StartsWith(isNegative ? "-0x" : "0x", StringComparison.OrdinalIgnoreCase); var isBinary = text.StartsWith(isNegative ? "-0b" : "0b", StringComparison.OrdinalIgnoreCase); var qualifiers = isHexadecimal ? QualifiersHex : Qualifiers; string? qualifier = null; if (qualifiers.Contains(last)) { int pos = text.Length - 1, count = 0; while (qualifiers.Contains(text[pos])) { ++count; --pos; } qualifier = text.Substring(text.Length - count, count); text = text.Substring(0, text.Length - count); } if (!isNegative) { if (isHexadecimal || isBinary) { text = text.Substring(2); } if (isBinary) { return ParseAsBinary(tokenPosition, text, isNegative); } if (!ulong.TryParse(text, isHexadecimal ? NumberStyles.HexNumber : NumberStyles.Integer, _culture, out ulong unsignedValue)) { throw new ParseException(string.Format(_culture, Res.InvalidIntegerLiteral, text), tokenPosition); } if (!string.IsNullOrEmpty(qualifier) && qualifier!.Length > 0) { if (qualifier == "U" || qualifier == "u") { return _constantExpressionHelper.CreateLiteral((uint)unsignedValue, text); } if (qualifier == "L" || qualifier == "l") { return _constantExpressionHelper.CreateLiteral((long)unsignedValue, text); } if (QualifiersReal.Contains(qualifier)) { return ParseRealLiteral(text, qualifier[0], false); } return _constantExpressionHelper.CreateLiteral(unsignedValue, text); } if (unsignedValue <= int.MaxValue) { return _constantExpressionHelper.CreateLiteral((int)unsignedValue, text); } if (unsignedValue <= uint.MaxValue) { return _constantExpressionHelper.CreateLiteral((uint)unsignedValue, text); } if (unsignedValue <= long.MaxValue) { return _constantExpressionHelper.CreateLiteral((long)unsignedValue, text); } return _constantExpressionHelper.CreateLiteral(unsignedValue, text); } if (isHexadecimal || isBinary) { text = text.Substring(3); } if (isBinary) { return ParseAsBinary(tokenPosition, text, isNegative); } if (!long.TryParse(text, isHexadecimal ? NumberStyles.HexNumber : NumberStyles.Integer, _culture, out long value)) { throw new ParseException(string.Format(_culture, Res.InvalidIntegerLiteral, text), tokenPosition); } if (isHexadecimal) { value = -value; } if (!string.IsNullOrEmpty(qualifier) && qualifier!.Length > 0) { if (qualifier == "L" || qualifier == "l") { return _constantExpressionHelper.CreateLiteral(value, text); } if (QualifiersReal.Contains(qualifier)) { return ParseRealLiteral(text, qualifier[0], false); } throw new ParseException(Res.MinusCannotBeAppliedToUnsignedInteger, tokenPosition); } if (value <= int.MaxValue) { return _constantExpressionHelper.CreateLiteral((int)value, text); } return _constantExpressionHelper.CreateLiteral(value, text); } /// <summary> /// Parse the text into a Real ConstantExpression. /// </summary> public Expression ParseRealLiteral(string text, char qualifier, bool stripQualifier) { if (stripQualifier) { var pos = text.Length - 1; while (pos >= 0 && Qualifiers.Contains(text[pos])) { pos--; } if (pos < text.Length - 1) { qualifier = text[pos + 1]; text = text.Substring(0, pos + 1); } } switch (qualifier) { case 'f': case 'F': return _constantExpressionHelper.CreateLiteral(ParseNumber(text, typeof(float))!, text); case 'm': case 'M': return _constantExpressionHelper.CreateLiteral(ParseNumber(text, typeof(decimal))!, text); case 'd': case 'D': return _constantExpressionHelper.CreateLiteral(ParseNumber(text, typeof(double))!, text); default: return _constantExpressionHelper.CreateLiteral(ParseNumber(text, typeof(double))!, text); } } /// <summary> /// Tries to parse the number (text) into the specified type. /// </summary> /// <param name="text">The text.</param> /// <param name="type">The type.</param> /// <param name="result">The result.</param> public bool TryParseNumber(string text, Type type, out object? result) { result = ParseNumber(text, type); return result != null; } /// <summary> /// Parses the number (text) into the specified type. /// </summary> /// <param name="text">The text.</param> /// <param name="type">The type.</param> public object? ParseNumber(string text, Type type) { try { #if !(UAP10_0 || NETSTANDARD) switch (Type.GetTypeCode(TypeHelper.GetNonNullableType(type))) { case TypeCode.SByte: return sbyte.Parse(text, _culture); case TypeCode.Byte: return byte.Parse(text, _culture); case TypeCode.Int16: return short.Parse(text, _culture); case TypeCode.UInt16: return ushort.Parse(text, _culture); case TypeCode.Int32: return int.Parse(text, _culture); case TypeCode.UInt32: return uint.Parse(text, _culture); case TypeCode.Int64: return long.Parse(text, _culture); case TypeCode.UInt64: return ulong.Parse(text, _culture); case TypeCode.Single: return float.Parse(text, _culture); case TypeCode.Double: return double.Parse(text, _culture); case TypeCode.Decimal: return decimal.Parse(text, _culture); } #else var tp = TypeHelper.GetNonNullableType(type); if (tp == typeof(sbyte)) { return sbyte.Parse(text, _culture); } if (tp == typeof(byte)) { return byte.Parse(text, _culture); } if (tp == typeof(short)) { return short.Parse(text, _culture); } if (tp == typeof(ushort)) { return ushort.Parse(text, _culture); } if (tp == typeof(int)) { return int.Parse(text, _culture); } if (tp == typeof(uint)) { return uint.Parse(text, _culture); } if (tp == typeof(long)) { return long.Parse(text, _culture); } if (tp == typeof(ulong)) { return ulong.Parse(text, _culture); } if (tp == typeof(float)) { return float.Parse(text, _culture); } if (tp == typeof(double)) { return double.Parse(text, _culture); } if (tp == typeof(decimal)) { return decimal.Parse(text, _culture); } #endif } catch { return null; } return null; } private Expression ParseAsBinary(int tokenPosition, string text, bool isNegative) { if (RegexBinary32.IsMatch(text)) { return _constantExpressionHelper.CreateLiteral((isNegative ? -1 : 1) * Convert.ToInt32(text, 2), text); } if (RegexBinary64.IsMatch(text)) { return _constantExpressionHelper.CreateLiteral((isNegative ? -1 : 1) * Convert.ToInt64(text, 2), text); } throw new ParseException(string.Format(_culture, Res.InvalidBinaryIntegerLiteral, text), tokenPosition); } } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/NumberParser.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
2,141
```smalltalk using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq.Dynamic.Core.Validation; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; namespace System.Linq.Dynamic.Core.Parser; internal class ExpressionHelper : IExpressionHelper { private readonly IConstantExpressionWrapper _constantExpressionWrapper = new ConstantExpressionWrapper(); private readonly ParsingConfig _parsingConfig; internal ExpressionHelper(ParsingConfig parsingConfig) { _parsingConfig = Check.NotNull(parsingConfig); } public void WrapConstantExpression(ref Expression argument) { if (_parsingConfig.UseParameterizedNamesInDynamicQuery) { _constantExpressionWrapper.Wrap(ref argument); } } public bool TryUnwrapAsValue<TValue>(Expression? expression, [NotNullWhen(true)] out TValue? value) { if (_parsingConfig.UseParameterizedNamesInDynamicQuery && _constantExpressionWrapper.TryUnwrapAsValue(expression as MemberExpression, out value)) { return true; } value = default; return false; } public bool TryUnwrapAsConstantExpression<TValue>(Expression? expression, [NotNullWhen(true)] out ConstantExpression? value) { if (_parsingConfig.UseParameterizedNamesInDynamicQuery && _constantExpressionWrapper.TryUnwrapAsConstantExpression<TValue>(expression as MemberExpression, out value)) { return true; } value = default; return false; } public bool TryUnwrapAsConstantExpression(Expression? expression, [NotNullWhen(true)] out ConstantExpression? value) { if (!_parsingConfig.UseParameterizedNamesInDynamicQuery || expression is not MemberExpression memberExpression) { value = default; return false; } if ( _constantExpressionWrapper.TryUnwrapAsConstantExpression<string>(memberExpression, out value) || _constantExpressionWrapper.TryUnwrapAsConstantExpression<int>(memberExpression, out value) || _constantExpressionWrapper.TryUnwrapAsConstantExpression<long>(memberExpression, out value) || _constantExpressionWrapper.TryUnwrapAsConstantExpression<short>(memberExpression, out value) ) { return true; } value = default; return false; } public bool ConvertNumericTypeToBiggestCommonTypeForBinaryOperator(ref Expression left, ref Expression right) { if (left.Type == right.Type) { return true; } if (left.Type == typeof(ulong) || right.Type == typeof(ulong)) { right = right.Type != typeof(ulong) ? Expression.Convert(right, typeof(ulong)) : right; left = left.Type != typeof(ulong) ? Expression.Convert(left, typeof(ulong)) : left; } else if (left.Type == typeof(long) || right.Type == typeof(long)) { right = right.Type != typeof(long) ? Expression.Convert(right, typeof(long)) : right; left = left.Type != typeof(long) ? Expression.Convert(left, typeof(long)) : left; } else if (left.Type == typeof(uint) || right.Type == typeof(uint)) { right = right.Type != typeof(uint) ? Expression.Convert(right, typeof(uint)) : right; left = left.Type != typeof(uint) ? Expression.Convert(left, typeof(uint)) : left; } else if (left.Type == typeof(int) || right.Type == typeof(int)) { right = right.Type != typeof(int) ? Expression.Convert(right, typeof(int)) : right; left = left.Type != typeof(int) ? Expression.Convert(left, typeof(int)) : left; } else if (left.Type == typeof(ushort) || right.Type == typeof(ushort)) { right = right.Type != typeof(ushort) ? Expression.Convert(right, typeof(ushort)) : right; left = left.Type != typeof(ushort) ? Expression.Convert(left, typeof(ushort)) : left; } else if (left.Type == typeof(short) || right.Type == typeof(short)) { right = right.Type != typeof(short) ? Expression.Convert(right, typeof(short)) : right; left = left.Type != typeof(short) ? Expression.Convert(left, typeof(short)) : left; } else if (left.Type == typeof(byte) || right.Type == typeof(byte)) { right = right.Type != typeof(byte) ? Expression.Convert(right, typeof(byte)) : right; left = left.Type != typeof(byte) ? Expression.Convert(left, typeof(byte)) : left; } return false; } public Expression GenerateAdd(Expression left, Expression right) { return Expression.Add(left, right); } public Expression GenerateStringConcat(Expression left, Expression right) { return GenerateStaticMethodCall("Concat", left, right); } public Expression GenerateSubtract(Expression left, Expression right) { return Expression.Subtract(left, right); } public Expression GenerateEqual(Expression left, Expression right) { OptimizeForEqualityIfPossible(ref left, ref right); TryConvertTypes(ref left, ref right); WrapConstantExpressions(ref left, ref right); return Expression.Equal(left, right); } public Expression GenerateNotEqual(Expression left, Expression right) { OptimizeForEqualityIfPossible(ref left, ref right); TryConvertTypes(ref left, ref right); WrapConstantExpressions(ref left, ref right); return Expression.NotEqual(left, right); } public Expression GenerateGreaterThan(Expression left, Expression right) { TryConvertTypes(ref left, ref right); if (left.Type == typeof(string)) { return Expression.GreaterThan(GenerateStaticMethodCall(nameof(string.Compare), left, right), Expression.Constant(0)); } if (left.Type.GetTypeInfo().IsEnum || right.Type.GetTypeInfo().IsEnum) { var leftPart = left.Type.GetTypeInfo().IsEnum ? Expression.Convert(left, Enum.GetUnderlyingType(left.Type)) : left; var rightPart = right.Type.GetTypeInfo().IsEnum ? Expression.Convert(right, Enum.GetUnderlyingType(right.Type)) : right; return Expression.GreaterThan(leftPart, rightPart); } WrapConstantExpressions(ref left, ref right); return Expression.GreaterThan(left, right); } public Expression GenerateGreaterThanEqual(Expression left, Expression right) { TryConvertTypes(ref left, ref right); if (left.Type == typeof(string)) { return Expression.GreaterThanOrEqual(GenerateStaticMethodCall(nameof(string.Compare), left, right), Expression.Constant(0)); } if (left.Type.GetTypeInfo().IsEnum || right.Type.GetTypeInfo().IsEnum) { return Expression.GreaterThanOrEqual( left.Type.GetTypeInfo().IsEnum ? Expression.Convert(left, Enum.GetUnderlyingType(left.Type)) : left, right.Type.GetTypeInfo().IsEnum ? Expression.Convert(right, Enum.GetUnderlyingType(right.Type)) : right ); } WrapConstantExpressions(ref left, ref right); return Expression.GreaterThanOrEqual(left, right); } public Expression GenerateLessThan(Expression left, Expression right) { TryConvertTypes(ref left, ref right); if (left.Type == typeof(string)) { return Expression.LessThan(GenerateStaticMethodCall(nameof(string.Compare), left, right), Expression.Constant(0)); } if (left.Type.GetTypeInfo().IsEnum || right.Type.GetTypeInfo().IsEnum) { return Expression.LessThan( left.Type.GetTypeInfo().IsEnum ? Expression.Convert(left, Enum.GetUnderlyingType(left.Type)) : left, right.Type.GetTypeInfo().IsEnum ? Expression.Convert(right, Enum.GetUnderlyingType(right.Type)) : right ); } WrapConstantExpressions(ref left, ref right); return Expression.LessThan(left, right); } public Expression GenerateLessThanEqual(Expression left, Expression right) { TryConvertTypes(ref left, ref right); if (left.Type == typeof(string)) { return Expression.LessThanOrEqual(GenerateStaticMethodCall(nameof(string.Compare), left, right), Expression.Constant(0)); } if (left.Type.GetTypeInfo().IsEnum || right.Type.GetTypeInfo().IsEnum) { return Expression.LessThanOrEqual( left.Type.GetTypeInfo().IsEnum ? Expression.Convert(left, Enum.GetUnderlyingType(left.Type)) : left, right.Type.GetTypeInfo().IsEnum ? Expression.Convert(right, Enum.GetUnderlyingType(right.Type)) : right ); } WrapConstantExpressions(ref left, ref right); return Expression.LessThanOrEqual(left, right); } public void OptimizeForEqualityIfPossible(ref Expression left, ref Expression right) { // The goal here is to provide the way to convert some types from the string form in a way that is compatible with Linq to Entities. // The Expression.Call(typeof(Guid).GetMethod("Parse"), right); does the job only for Linq to Object but Linq to Entities. Type leftType = left.Type; Type rightType = right.Type; if (rightType == typeof(string) && right.NodeType == ExpressionType.Constant) { right = OptimizeStringForEqualityIfPossible((string?)((ConstantExpression)right).Value, leftType) ?? right; } if (leftType == typeof(string) && left.NodeType == ExpressionType.Constant) { left = OptimizeStringForEqualityIfPossible((string?)((ConstantExpression)left).Value, rightType) ?? left; } } public Expression? OptimizeStringForEqualityIfPossible(string? text, Type type) { if (type == typeof(DateTime) && DateTime.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.None, out var dateTime)) { return Expression.Constant(dateTime, typeof(DateTime)); } #if NET6_0_OR_GREATER if (type == typeof(DateOnly) && DateOnly.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.None, out var dateOnly)) { return Expression.Constant(dateOnly, typeof(DateOnly)); } if (type == typeof(TimeOnly) && TimeOnly.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.None, out var timeOnly)) { return Expression.Constant(timeOnly, typeof(TimeOnly)); } #endif #if !NET35 if (type == typeof(Guid) && Guid.TryParse(text, out var guid)) { return Expression.Constant(guid, typeof(Guid)); } #else try { return Expression.Constant(new Guid(text!)); } catch { // Doing it in old fashion way when no TryParse interface was provided by .NET } #endif return null; } public bool MemberExpressionIsDynamic(Expression expression) { #if NET35 return false; #else return expression is MemberExpression memberExpression && memberExpression.Member.GetCustomAttribute<DynamicAttribute>() != null; #endif } public Expression ConvertToExpandoObjectAndCreateDynamicExpression(Expression expression, Type type, string propertyName) { #if !NET35 && !UAP10_0 && !NETSTANDARD1_3 return Expression.Dynamic(new DynamicGetMemberBinder(propertyName, _parsingConfig), type, expression); #else throw new NotSupportedException(Res.DynamicExpandoObjectIsNotSupported); #endif } private void WrapConstantExpressions(ref Expression left, ref Expression right) { if (_parsingConfig.UseParameterizedNamesInDynamicQuery) { _constantExpressionWrapper.Wrap(ref left); _constantExpressionWrapper.Wrap(ref right); } } public bool TryGenerateAndAlsoNotNullExpression(Expression sourceExpression, bool addSelf, out Expression generatedExpression) { var expressions = CollectExpressions(addSelf, sourceExpression); if (expressions.Count == 1 && !(expressions[0] is MethodCallExpression)) { generatedExpression = sourceExpression; return false; } // Reverse the list expressions.Reverse(); // Convert all expressions into '!= null' expressions (only if the type can be null) var binaryExpressions = expressions .Where(expression => TypeHelper.TypeCanBeNull(expression.Type)) .Select(expression => Expression.NotEqual(expression, Expression.Constant(null))) .ToArray(); // Convert all binary expressions into `AndAlso(...)` generatedExpression = binaryExpressions[0]; for (int i = 1; i < binaryExpressions.Length; i++) { generatedExpression = Expression.AndAlso(generatedExpression, binaryExpressions[i]); } return true; } public bool ExpressionQualifiesForNullPropagation(Expression? expression) { return expression is MemberExpression or ParameterExpression or MethodCallExpression or UnaryExpression; } public Expression GenerateDefaultExpression(Type type) { #if NET35 return Expression.Constant(Activator.CreateInstance(type)); #else return Expression.Default(type); #endif } public Expression ConvertAnyArrayToObjectArray(Expression arrayExpression) { Check.NotNull(arrayExpression); return Expression.Call( null, typeof(ExpressionHelper).GetMethod(nameof(ConvertIfIEnumerableHasValues), BindingFlags.Static | BindingFlags.NonPublic)!, arrayExpression ); } private Expression? GetMemberExpression(Expression? expression) { if (ExpressionQualifiesForNullPropagation(expression)) { return expression; } if (expression is LambdaExpression lambdaExpression) { if (lambdaExpression.Body is MemberExpression bodyAsMemberExpression) { return bodyAsMemberExpression; } if (lambdaExpression.Body is UnaryExpression bodyAsUnaryExpression) { return bodyAsUnaryExpression.Operand; } } return null; } private List<Expression> CollectExpressions(bool addSelf, Expression sourceExpression) { var expression = GetMemberExpression(sourceExpression); var list = new List<Expression>(); if (addSelf) { switch (expression) { case MemberExpression: list.Add(sourceExpression); break; // ReSharper disable once RedundantEmptySwitchSection default: break; } } bool expressionRecognized; do { switch (expression) { case MemberExpression memberExpression: expression = GetMemberExpression(memberExpression.Expression); expressionRecognized = expression != null; break; case MethodCallExpression methodCallExpression: expression = GetMethodCallExpression(methodCallExpression); expressionRecognized = expression != null; break; case UnaryExpression unaryExpression: expression = GetUnaryExpression(unaryExpression); expressionRecognized = expression != null; break; default: expressionRecognized = false; break; } if (expressionRecognized && ExpressionQualifiesForNullPropagation(expression)) { list.Add(expression!); } } while (expressionRecognized); return list; } /// <summary> /// If the types are different (and not null), try to convert the object type to other type. /// </summary> private void TryConvertTypes(ref Expression left, ref Expression right) { if (!_parsingConfig.ConvertObjectToSupportComparison || left.Type == right.Type || Constants.IsNull(left) || Constants.IsNull(right)) { return; } if (left.Type == typeof(object)) { left = Expression.Convert(left, right.Type); } else if (right.Type == typeof(object)) { right = Expression.Convert(right, left.Type); } } private static Expression GenerateStaticMethodCall(string methodName, Expression left, Expression right) { return Expression.Call(null, GetStaticMethod(methodName, left, right), new[] { left, right }); } private static MethodInfo GetStaticMethod(string methodName, Expression left, Expression right) { var methodInfo = left.Type.GetMethod(methodName, new[] { left.Type, right.Type }); if (methodInfo == null) { methodInfo = right.Type.GetMethod(methodName, new[] { left.Type, right.Type })!; } return methodInfo; } private static Expression? GetMethodCallExpression(MethodCallExpression methodCallExpression) { if (methodCallExpression.Object != null) { // Something like: "np(FooValue.Zero().Length)" return methodCallExpression.Object; } // Something like: "np(MyClasses.FirstOrDefault())" return methodCallExpression.Arguments.FirstOrDefault(); } private static Expression? GetUnaryExpression(UnaryExpression? unaryExpression) { return unaryExpression?.Operand; } private static object[] ConvertIfIEnumerableHasValues(IEnumerable? input) { // ReSharper disable once PossibleMultipleEnumeration if (input != null && input.Cast<object>().Any()) { // ReSharper disable once PossibleMultipleEnumeration return input.Cast<object>().ToArray(); } return new object[0]; } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/ExpressionHelper.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
3,548
```smalltalk using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; #if UAP10_0 || NETSTANDARD1_3 using System.Reflection; #endif namespace System.Linq.Dynamic.Core.Parser; /// <summary> /// Based on gblog by graeme-hill. path_to_url /// </summary> internal class ConstantExpressionWrapper : IConstantExpressionWrapper { public void Wrap(ref Expression expression) { if (expression is ConstantExpression constantExpression) { if (constantExpression.Type == typeof(bool)) { expression = Wrap((bool)constantExpression.Value); } else if (constantExpression.Type == typeof(bool?)) { expression = Wrap((bool?)constantExpression.Value); } else if (constantExpression.Type == typeof(char)) { expression = Wrap((char)constantExpression.Value); } else if (constantExpression.Type == typeof(char?)) { expression = Wrap((char?)constantExpression.Value); } else if (constantExpression.Type == typeof(byte)) { expression = Wrap((byte)constantExpression.Value); } else if (constantExpression.Type == typeof(byte?)) { expression = Wrap((byte?)constantExpression.Value); } else if (constantExpression.Type == typeof(sbyte)) { expression = Wrap((sbyte)constantExpression.Value); } else if (constantExpression.Type == typeof(string)) { expression = Wrap((string)constantExpression.Value); } else if (constantExpression.Type == typeof(float)) { expression = Wrap((float)constantExpression.Value); } else if (constantExpression.Type == typeof(float?)) { expression = Wrap((float?)constantExpression.Value); } else if (constantExpression.Type == typeof(decimal)) { expression = Wrap((decimal)constantExpression.Value); } else if (constantExpression.Type == typeof(decimal?)) { expression = Wrap((decimal?)constantExpression.Value); } else if (constantExpression.Type == typeof(double)) { expression = Wrap((double)constantExpression.Value); } else if (constantExpression.Type == typeof(double?)) { expression = Wrap((double?)constantExpression.Value); } else if (constantExpression.Type == typeof(long)) { expression = Wrap((long)constantExpression.Value); } else if (constantExpression.Type == typeof(long?)) { expression = Wrap((long?)constantExpression.Value); } else if (constantExpression.Type == typeof(ulong)) { expression = Wrap((ulong)constantExpression.Value); } else if (constantExpression.Type == typeof(ulong?)) { expression = Wrap((ulong?)constantExpression.Value); } else if (constantExpression.Type == typeof(int)) { expression = Wrap((int)constantExpression.Value); } else if (constantExpression.Type == typeof(int?)) { expression = Wrap((int?)constantExpression.Value); } else if (constantExpression.Type == typeof(uint)) { expression = Wrap((uint)constantExpression.Value); } else if (constantExpression.Type == typeof(uint?)) { expression = Wrap((uint?)constantExpression.Value); } else if (constantExpression.Type == typeof(short)) { expression = Wrap((short)constantExpression.Value); } else if (constantExpression.Type == typeof(short?)) { expression = Wrap((short?)constantExpression.Value); } else if (constantExpression.Type == typeof(ushort)) { expression = Wrap((ushort)constantExpression.Value); } else if (constantExpression.Type == typeof(ushort?)) { expression = Wrap((ushort?)constantExpression.Value); } else if (constantExpression.Type == typeof(Guid)) { expression = Wrap((Guid)constantExpression.Value); } else if (constantExpression.Type == typeof(Guid?)) { expression = Wrap((Guid?)constantExpression.Value); } else if (constantExpression.Type == typeof(DateTime)) { expression = Wrap((DateTime)constantExpression.Value); } else if (constantExpression.Type == typeof(DateTime?)) { expression = Wrap((DateTime?)constantExpression.Value); } else if (constantExpression.Type == typeof(DateTimeOffset)) { expression = Wrap((DateTimeOffset)constantExpression.Value); } else if (constantExpression.Type == typeof(DateTimeOffset?)) { expression = Wrap((DateTimeOffset?)constantExpression.Value); } else if (constantExpression.Type == typeof(TimeSpan)) { expression = Wrap((TimeSpan)constantExpression.Value); } else if (constantExpression.Type == typeof(TimeSpan?)) { expression = Wrap((TimeSpan?)constantExpression.Value); } #if NET6_0_OR_GREATER else if (constantExpression.Type == typeof(DateOnly)) { expression = Wrap((DateOnly)constantExpression.Value); } else if (constantExpression.Type == typeof(DateOnly?)) { expression = Wrap((DateOnly?)constantExpression.Value); } else if (constantExpression.Type == typeof(TimeOnly)) { expression = Wrap((TimeOnly)constantExpression.Value); } else if (constantExpression.Type == typeof(TimeOnly?)) { expression = Wrap((TimeOnly?)constantExpression.Value); } #endif return; } if (expression is NewExpression newExpression) { if (newExpression.Type == typeof(Guid)) { expression = Wrap(Expression.Lambda<Func<Guid>>(newExpression).Compile()()); } else if (newExpression.Type == typeof(Guid?)) { expression = Wrap(Expression.Lambda<Func<Guid?>>(newExpression).Compile()()); } else if (newExpression.Type == typeof(DateTime)) { expression = Wrap(Expression.Lambda<Func<DateTime>>(newExpression).Compile()()); } else if (newExpression.Type == typeof(DateTime?)) { expression = Wrap(Expression.Lambda<Func<DateTime?>>(newExpression).Compile()()); } else if (newExpression.Type == typeof(DateTimeOffset)) { expression = Wrap(Expression.Lambda<Func<DateTimeOffset>>(newExpression).Compile()()); } else if (newExpression.Type == typeof(DateTimeOffset?)) { expression = Wrap(Expression.Lambda<Func<DateTimeOffset?>>(newExpression).Compile()()); } else if (newExpression.Type == typeof(TimeSpan)) { expression = Wrap(Expression.Lambda<Func<TimeSpan>>(newExpression).Compile()()); } else if (newExpression.Type == typeof(TimeSpan?)) { expression = Wrap(Expression.Lambda<Func<TimeSpan?>>(newExpression).Compile()()); } #if NET6_0_OR_GREATER else if (newExpression.Type == typeof(DateOnly)) { expression = Wrap(Expression.Lambda<Func<DateOnly>>(newExpression).Compile()()); } else if (newExpression.Type == typeof(DateOnly?)) { expression = Wrap(Expression.Lambda<Func<DateOnly?>>(newExpression).Compile()()); } else if (newExpression.Type == typeof(TimeOnly)) { expression = Wrap(Expression.Lambda<Func<TimeOnly>>(newExpression).Compile()()); } else if (newExpression.Type == typeof(TimeOnly?)) { expression = Wrap(Expression.Lambda<Func<TimeOnly?>>(newExpression).Compile()()); } #endif } } public bool TryUnwrapAsValue<TValue>(MemberExpression? expression, [NotNullWhen(true)] out TValue? value) { if (expression?.Expression is ConstantExpression { Value: WrappedValue<TValue> wrapper }) { value = wrapper.Value!; return true; } value = default; return false; } public bool TryUnwrapAsConstantExpression<TValue>(MemberExpression? expression, [NotNullWhen(true)] out ConstantExpression? value) { if (TryUnwrapAsValue<TValue>(expression, out var wrappedValue)) { value = Expression.Constant(wrappedValue); return true; } value = default; return false; } private static MemberExpression Wrap<TValue>(TValue value) { var wrapper = new WrappedValue<TValue>(value); return Expression.Property(Expression.Constant(wrapper), typeof(WrappedValue<TValue>).GetProperty("Value")!); } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/ConstantExpressionWrapper.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
1,763
```smalltalk using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; namespace System.Linq.Dynamic.Core.Parser; internal interface IExpressionHelper { bool ConvertNumericTypeToBiggestCommonTypeForBinaryOperator(ref Expression left, ref Expression right); Expression GenerateAdd(Expression left, Expression right); Expression GenerateEqual(Expression left, Expression right); Expression GenerateGreaterThan(Expression left, Expression right); Expression GenerateGreaterThanEqual(Expression left, Expression right); Expression GenerateLessThan(Expression left, Expression right); Expression GenerateLessThanEqual(Expression left, Expression right); Expression GenerateNotEqual(Expression left, Expression right); Expression GenerateStringConcat(Expression left, Expression right); Expression GenerateSubtract(Expression left, Expression right); void OptimizeForEqualityIfPossible(ref Expression left, ref Expression right); Expression? OptimizeStringForEqualityIfPossible(string text, Type type); bool TryGenerateAndAlsoNotNullExpression(Expression sourceExpression, bool addSelf, out Expression generatedExpression); bool ExpressionQualifiesForNullPropagation(Expression expression); void WrapConstantExpression(ref Expression argument); bool TryUnwrapAsValue<TValue>(Expression? expression, [NotNullWhen(true)] out TValue? value); bool TryUnwrapAsConstantExpression<TValue>(Expression? expression, [NotNullWhen(true)] out ConstantExpression? value); bool TryUnwrapAsConstantExpression(Expression? expression, [NotNullWhen(true)] out ConstantExpression? value); bool MemberExpressionIsDynamic(Expression expression); Expression ConvertToExpandoObjectAndCreateDynamicExpression(Expression expression, Type type, string propertyName); Expression GenerateDefaultExpression(Type type); Expression ConvertAnyArrayToObjectArray(Expression arrayExpression); } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/IExpressionHelper.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
338
```smalltalk using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq.Dynamic.Core.Validation; using System.Reflection; namespace System.Linq.Dynamic.Core.Parser; internal static class TypeHelper { public static bool TryGetFirstGenericArgument(Type type, [NotNullWhen(true)] out Type? genericType) { var genericArguments = type.GetTypeInfo().GetGenericTypeArguments(); if (genericArguments.Length == 0) { genericType = null; return false; } genericType = genericArguments[0]; return true; } public static bool TryFindGenericType(Type generic, Type? type, [NotNullWhen(true)] out Type? foundType) { while (type != null && type != typeof(object)) { if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == generic) { foundType = type; return true; } if (generic.GetTypeInfo().IsInterface) { foreach (var interfaceType in type.GetInterfaces()) { if (TryFindGenericType(generic, interfaceType, out foundType)) { return true; } } } type = type.GetTypeInfo().BaseType; } foundType = null; return false; } public static bool IsCompatibleWith(Type source, Type target) { #if !(UAP10_0 || NETSTANDARD) if (source == target) { return true; } if (!target.IsValueType) { return target.IsAssignableFrom(source); } Type st = GetNonNullableType(source); Type tt = GetNonNullableType(target); if (st != source && tt == target) { return false; } TypeCode sc = st.GetTypeInfo().IsEnum ? TypeCode.Int64 : Type.GetTypeCode(st); TypeCode tc = tt.GetTypeInfo().IsEnum ? TypeCode.Int64 : Type.GetTypeCode(tt); switch (sc) { case TypeCode.SByte: switch (tc) { case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.Byte: switch (tc) { case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.Int16: switch (tc) { case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.UInt16: switch (tc) { case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.Int32: switch (tc) { case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.UInt32: switch (tc) { case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.Int64: switch (tc) { case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.UInt64: switch (tc) { case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.Single: switch (tc) { case TypeCode.Single: case TypeCode.Double: return true; } break; default: if (st == tt) { return true; } break; } return false; #else if (source == target) { return true; } if (!target.GetTypeInfo().IsValueType) { return target.IsAssignableFrom(source); } Type st = GetNonNullableType(source); Type tt = GetNonNullableType(target); if (st != source && tt == target) { return false; } Type sc = st.GetTypeInfo().IsEnum ? typeof(object) : st; Type tc = tt.GetTypeInfo().IsEnum ? typeof(object) : tt; if (sc == typeof(sbyte)) { if (tc == typeof(sbyte) || tc == typeof(short) || tc == typeof(int) || tc == typeof(long) || tc == typeof(float) || tc == typeof(double) || tc == typeof(decimal)) return true; } else if (sc == typeof(byte)) { if (tc == typeof(byte) || tc == typeof(short) || tc == typeof(ushort) || tc == typeof(int) || tc == typeof(uint) || tc == typeof(long) || tc == typeof(ulong) || tc == typeof(float) || tc == typeof(double) || tc == typeof(decimal)) return true; } else if (sc == typeof(short)) { if (tc == typeof(short) || tc == typeof(int) || tc == typeof(long) || tc == typeof(float) || tc == typeof(double) || tc == typeof(decimal)) return true; } else if (sc == typeof(ushort)) { if (tc == typeof(ushort) || tc == typeof(int) || tc == typeof(uint) || tc == typeof(long) || tc == typeof(ulong) || tc == typeof(float) || tc == typeof(double) || tc == typeof(decimal)) return true; } else if (sc == typeof(int)) { if (tc == typeof(int) || tc == typeof(long) || tc == typeof(float) || tc == typeof(double) || tc == typeof(decimal)) return true; } else if (sc == typeof(uint)) { if (tc == typeof(uint) || tc == typeof(long) || tc == typeof(ulong) || tc == typeof(float) || tc == typeof(double) || tc == typeof(decimal)) return true; } else if (sc == typeof(long)) { if (tc == typeof(long) || tc == typeof(float) || tc == typeof(double) || tc == typeof(decimal)) return true; } else if (sc == typeof(ulong)) { if (tc == typeof(ulong) || tc == typeof(float) || tc == typeof(double) || tc == typeof(decimal)) return true; } else if (sc == typeof(float)) { if (tc == typeof(float) || tc == typeof(double)) return true; } if (st == tt) { return true; } return false; #endif } public static bool IsClass(Type type) { bool result = false; if (type.GetTypeInfo().IsClass) { // Is Class or Delegate if (type != typeof(Delegate)) { result = true; } } return result; } public static bool IsStruct(Type type) { var nonNullableType = GetNonNullableType(type); if (nonNullableType.GetTypeInfo().IsValueType) { if (!nonNullableType.GetTypeInfo().IsPrimitive) { if ( #if NET6_0_OR_GREATER nonNullableType != typeof(DateOnly) && nonNullableType != typeof(TimeOnly) && #endif nonNullableType != typeof(decimal) && nonNullableType != typeof(DateTime) && nonNullableType != typeof(Guid) ) { if (!nonNullableType.GetTypeInfo().IsEnum) { return true; } } } } return false; } public static bool IsEnumType(Type type) { return GetNonNullableType(type).GetTypeInfo().IsEnum; } public static bool IsNumericType(Type type) { return GetNumericTypeKind(type) != 0; } public static bool IsNullableType(Type type) { Check.NotNull(type, nameof(type)); return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } public static bool TypeCanBeNull(Type type) { Check.NotNull(type); return !type.GetTypeInfo().IsValueType || IsNullableType(type); } public static Type ToNullableType(Type type) { Check.NotNull(type); if (IsNullableType(type)) { // Already nullable, just return the type. return type; } if (!type.GetTypeInfo().IsValueType) { // Type is a not a value type, just return the type. return type; } // Convert type to a nullable type return typeof(Nullable<>).MakeGenericType(type); } public static bool IsSignedIntegralType(Type type) { return GetNumericTypeKind(type) == 2; } public static bool IsUnsignedIntegralType(Type type) { return GetNumericTypeKind(type) == 3; } private static int GetNumericTypeKind(Type type) { type = GetNonNullableType(type); #if !(UAP10_0 || NETSTANDARD) if (type.GetTypeInfo().IsEnum) { return 0; } switch (Type.GetTypeCode(type)) { case TypeCode.Char: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return 1; case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: return 2; case TypeCode.Byte: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: return 3; default: return 0; } #else if (type.GetTypeInfo().IsEnum) { return 0; } if (type == typeof(char) || type == typeof(float) || type == typeof(double) || type == typeof(decimal)) return 1; if (type == typeof(sbyte) || type == typeof(short) || type == typeof(int) || type == typeof(long)) return 2; if (type == typeof(byte) || type == typeof(ushort) || type == typeof(uint) || type == typeof(ulong)) return 3; return 0; #endif } public static string GetTypeName(Type? type) { if (type == null) { return "null"; } Type baseType = GetNonNullableType(type); string name = baseType.Name; if (type != baseType) { name += '?'; } return name; } public static Type GetNullableType(Type type) { type = Nullable.GetUnderlyingType(type) ?? type; return type.GetTypeInfo().IsValueType ? typeof(Nullable<>).MakeGenericType(type) : type; } public static Type GetNonNullableType(Type type) { Check.NotNull(type, nameof(type)); return IsNullableType(type) ? type.GetTypeInfo().GetGenericTypeArguments()[0] : type; } public static Type GetUnderlyingType(Type type) { Check.NotNull(type, nameof(type)); Type[] genericTypeArguments = type.GetGenericArguments(); if (genericTypeArguments.Any()) { var outerType = GetUnderlyingType(genericTypeArguments.LastOrDefault()!); return Nullable.GetUnderlyingType(type) == outerType ? type : outerType; } return type; } public static IList<Type> GetSelfAndBaseTypes(Type type, bool excludeObject = false) { Check.NotNull(type); if (type.GetTypeInfo().IsInterface) { var types = new List<Type>(); AddInterface(types, type); return types; } return GetSelfAndBaseClasses(type).Where(t => !excludeObject || t != typeof(object)).ToList(); } private static IEnumerable<Type> GetSelfAndBaseClasses(Type? type) { while (type != null) { yield return type; type = type.GetTypeInfo().BaseType; } } private static void AddInterface(ICollection<Type> types, Type type) { if (!types.Contains(type)) { types.Add(type); foreach (Type t in type.GetInterfaces()) { AddInterface(types, t); } } } public static bool TryParseEnum(string value, Type? type, [NotNullWhen(true)] out object? enumValue) { if (type is { } && type.GetTypeInfo().IsEnum && Enum.IsDefined(type, value)) { enumValue = Enum.Parse(type, value, true); return true; } enumValue = null; return false; } public static bool IsDictionary(Type? type) { return TryFindGenericType(typeof(IDictionary<,>), type, out _) || #if NET35 || NET40 // ReSharper disable once RedundantLogicalConditionalExpressionOperand false; #else TryFindGenericType(typeof(IReadOnlyDictionary<,>), type, out _); #endif } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/TypeHelper.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
2,985
```smalltalk using System.Linq.Expressions; namespace System.Linq.Dynamic.Core.Parser { interface ITypeFinder { Type? FindTypeByName(string name, ParameterExpression?[]? expressions, bool forceUseCustomTypeProvider); } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/ITypeFinder.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
48
```smalltalk using System.Diagnostics.CodeAnalysis; namespace System.Linq.Dynamic.Core.Parser; interface IKeywordsHelper { bool TryGetValue(string name, [NotNullWhen(true)] out object? keyWordOrType); } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/IKeywordsHelper.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
40
```smalltalk using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq.Dynamic.Core.Validation; using System.Linq.Expressions; namespace System.Linq.Dynamic.Core.Parser; internal class KeywordsHelper : IKeywordsHelper { public const string KEYWORD_IT = "it"; public const string KEYWORD_PARENT = "parent"; public const string KEYWORD_ROOT = "root"; public const string SYMBOL_IT = "$"; public const string SYMBOL_PARENT = "^"; public const string SYMBOL_ROOT = "~"; public const string FUNCTION_IIF = "iif"; public const string FUNCTION_ISNULL = "isnull"; public const string FUNCTION_NEW = "new"; public const string FUNCTION_NULLPROPAGATION = "np"; public const string FUNCTION_IS = "is"; public const string FUNCTION_AS = "as"; public const string FUNCTION_CAST = "cast"; private readonly ParsingConfig _config; // Keywords are IgnoreCase private readonly Dictionary<string, object> _keywordMapping = new(StringComparer.OrdinalIgnoreCase) { { "true", Expression.Constant(true) }, { "false", Expression.Constant(false) }, { "null", Expression.Constant(null) }, { SYMBOL_IT, SYMBOL_IT }, { SYMBOL_PARENT, SYMBOL_PARENT }, { SYMBOL_ROOT, SYMBOL_ROOT }, { FUNCTION_IIF, FUNCTION_IIF }, { FUNCTION_ISNULL, FUNCTION_ISNULL }, { FUNCTION_NEW, FUNCTION_NEW }, { FUNCTION_NULLPROPAGATION, FUNCTION_NULLPROPAGATION }, { FUNCTION_IS, FUNCTION_IS }, { FUNCTION_AS, FUNCTION_AS }, { FUNCTION_CAST, FUNCTION_CAST } }; // PreDefined Types are not IgnoreCase private static readonly Dictionary<string, object> PreDefinedTypeMapping = new(); // Custom DefinedTypes are not IgnoreCase private readonly Dictionary<string, object> _customTypeMapping = new(); static KeywordsHelper() { foreach (var type in PredefinedTypesHelper.PredefinedTypes.OrderBy(kvp => kvp.Value).Select(kvp => kvp.Key)) { PreDefinedTypeMapping[type.FullName!] = type; PreDefinedTypeMapping[type.Name] = type; } } public KeywordsHelper(ParsingConfig config) { _config = Check.NotNull(config); if (config.AreContextKeywordsEnabled) { _keywordMapping.Add(KEYWORD_IT, KEYWORD_IT); _keywordMapping.Add(KEYWORD_PARENT, KEYWORD_PARENT); _keywordMapping.Add(KEYWORD_ROOT, KEYWORD_ROOT); } // ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract if (config.CustomTypeProvider != null) { foreach (var type in config.CustomTypeProvider.GetCustomTypes()) { _customTypeMapping[type.FullName!] = type; _customTypeMapping[type.Name] = type; } } } public bool TryGetValue(string name, [NotNullWhen(true)] out object? keyWordOrType) { // 1. Try to get as keyword if (_keywordMapping.TryGetValue(name, out var keyWord)) { keyWordOrType = keyWord; return true; } // 2. Try to get as predefined shorttype ("bool", "char", ...) if (PredefinedTypesHelper.PredefinedTypesShorthands.TryGetValue(name, out var predefinedShortHandType)) { keyWordOrType = predefinedShortHandType; return true; } // 3. Try to get as predefined type ("Boolean", "System.Boolean", ..., "DateTime", "System.DateTime", ...) if (PreDefinedTypeMapping.TryGetValue(name, out var predefinedType)) { keyWordOrType = predefinedType; return true; } // 4. Try to get as an enum from the system namespace if (_config.SupportEnumerationsFromSystemNamespace && EnumerationsFromMscorlib.PredefinedEnumerationTypes.TryGetValue(name, out var predefinedEnumType)) { keyWordOrType = predefinedEnumType; return true; } // 5. Try to get as custom type if (_customTypeMapping.TryGetValue(name, out var customType)) { keyWordOrType = customType; return true; } // 6. Not found, return false keyWordOrType = null; return false; } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/KeywordsHelper.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
909
```smalltalk namespace System.Linq.Dynamic.Core.Parser; internal static class ConstantExpressionHelperFactory { private static readonly object Lock = new(); private static ConstantExpressionHelper? _instance; public static ConstantExpressionHelper GetInstance(ParsingConfig config) { if (_instance == null) { lock (Lock) { _instance ??= new ConstantExpressionHelper(config); } } return _instance; } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/ConstantExpressionHelperFactory.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
90
```smalltalk using System.Linq.Dynamic.Core.Validation; using System.Linq.Expressions; namespace System.Linq.Dynamic.Core.Parser { internal class TypeFinder : ITypeFinder { private readonly IKeywordsHelper _keywordsHelper; private readonly ParsingConfig _parsingConfig; public TypeFinder(ParsingConfig parsingConfig, IKeywordsHelper keywordsHelper) { Check.NotNull(parsingConfig); Check.NotNull(keywordsHelper); _keywordsHelper = keywordsHelper; _parsingConfig = parsingConfig; } public Type? FindTypeByName(string name, ParameterExpression?[]? expressions, bool forceUseCustomTypeProvider) { Check.NotEmpty(name); _keywordsHelper.TryGetValue(name, out var type); if (type is Type sameType) { return sameType; } if (expressions != null && TryResolveTypeUsingExpressions(name, expressions, out var resolvedType)) { return resolvedType; } return ResolveTypeByUsingCustomTypeProvider(name, forceUseCustomTypeProvider); } private Type? ResolveTypeByUsingCustomTypeProvider(string name, bool forceUseCustomTypeProvider) { if ((forceUseCustomTypeProvider || _parsingConfig.AllowNewToEvaluateAnyType) && _parsingConfig.CustomTypeProvider != null) { var resolvedType = _parsingConfig.CustomTypeProvider.ResolveType(name); if (resolvedType != null) { return resolvedType; } // In case the type is not found based on fullname, try to get the type on simplename if allowed if (_parsingConfig.ResolveTypesBySimpleName) { return _parsingConfig.CustomTypeProvider.ResolveTypeBySimpleName(name); } } return null; } private bool TryResolveTypeUsingExpressions(string name, ParameterExpression?[] expressions, out Type? result) { foreach (var expression in expressions.Where(e => e != null)) { if (name == expression!.Type.Name) { result = expression.Type; return true; } if (name == $"{expression.Type.Namespace}.{expression.Type.Name}") { result = expression.Type; return true; } if (_parsingConfig.ResolveTypesBySimpleName && _parsingConfig.CustomTypeProvider != null) { string possibleFullName = $"{expression.Type.Namespace}.{name}"; var resolvedType = _parsingConfig.CustomTypeProvider.ResolveType(possibleFullName); if (resolvedType != null) { result = resolvedType; return true; } } } result = null; return false; } } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/TypeFinder.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
551
```smalltalk using System.Collections.Concurrent; using System.Collections.Generic; using System.Reflection; namespace System.Linq.Dynamic.Core.Parser { internal static class EnumerationsFromMscorlib { /// <summary> /// All Enum types from mscorlib/netstandard. /// </summary> public static readonly IDictionary<string, Type> PredefinedEnumerationTypes = new ConcurrentDictionary<string, Type>(); static EnumerationsFromMscorlib() { var list = new List<Type>(AddEnumsFromAssembly(typeof(UriFormat).GetTypeInfo().Assembly.FullName)); #if !(UAP10_0 || NETSTANDARD || NET35 || NETCOREAPP) list.AddRange(AddEnumsFromAssembly("mscorlib")); #else list.AddRange(AddEnumsFromAssembly("System.Runtime")); list.AddRange(AddEnumsFromAssembly("System.Private.Corelib")); #endif foreach (var group in list.GroupBy(t => t.Name)) { Add(group); } } private static IEnumerable<Type> AddEnumsFromAssembly(string assemblyName) { try { return Assembly.Load(new AssemblyName(assemblyName)).GetTypes().Where(t => t.GetTypeInfo().IsEnum && t.GetTypeInfo().IsPublic); } catch { return Enumerable.Empty<Type>(); } } private static void Add(IGrouping<string, Type> group) { if (group.Count() == 1) { var singleType = group.Single(); PredefinedEnumerationTypes.Add(group.Key, singleType); PredefinedEnumerationTypes.Add(singleType.FullName, singleType); } else { foreach (var fullType in group) { PredefinedEnumerationTypes.Add(fullType.FullName, fullType); } } } } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/EnumerationsFromMscorlib.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
372
```smalltalk using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq.Dynamic.Core.Validation; namespace System.Linq.Dynamic.Core.Parser; internal static class PredefinedTypesHelper { // These shorthands have different name than actual type and therefore not recognized by default from the PredefinedTypes. public static readonly IDictionary<string, Type> PredefinedTypesShorthands = new Dictionary<string, Type> { { "bool", typeof(bool) }, { "byte", typeof(byte) }, { "char", typeof(char) }, { "decimal", typeof(decimal) }, { "double", typeof(double) }, { "float", typeof(float) }, { "int", typeof(int) }, { "long", typeof(long) }, { "object", typeof(object) }, { "sbyte", typeof(sbyte) }, { "short", typeof(short) }, { "string", typeof(string) }, { "uint", typeof(uint) }, { "ulong", typeof(ulong) }, { "ushort", typeof(ushort) } }; public static readonly IDictionary<Type, int> PredefinedTypes = new ConcurrentDictionary<Type, int>(new Dictionary<Type, int> { { typeof(object), 0 }, { typeof(bool), 0 }, { typeof(char), 0 }, { typeof(string), 0 }, { typeof(sbyte), 0 }, { typeof(byte), 0 }, { typeof(short), 0 }, { typeof(ushort), 0 }, { typeof(int), 0 }, { typeof(uint), 0 }, { typeof(long), 0 }, { typeof(ulong), 0 }, { typeof(float), 0 }, { typeof(double), 0 }, { typeof(decimal), 0 }, { typeof(DateTime), 0 }, { typeof(DateTimeOffset), 0 }, { typeof(TimeSpan), 0 }, { typeof(Guid), 0 }, { typeof(Math), 0 }, { typeof(Convert), 0 }, { typeof(Uri), 0 }, { typeof(Enum), 0 }, #if NET6_0_OR_GREATER { typeof(DateOnly), 0 }, { typeof(TimeOnly), 0 } #endif }); static PredefinedTypesHelper() { // Only add these types for full .NET Framework and .NETStandard 2.1 // And only if the EntityFramework.DynamicLinq is available. #if NET452_OR_GREATER || NETSTANDARD2_1 if (Type.GetType("EntityFramework.DynamicLinq.EFType, EntityFramework.DynamicLinq") != null) { TryAdd("System.Data.Objects.EntityFunctions, System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", 1); TryAdd("System.Data.Objects.SqlClient.SqlFunctions, System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", 1); TryAdd("System.Data.Objects.SqlClient.SqlSpatialFunctions, System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", 1); TryAdd("System.Data.Entity.Core.Objects.EntityFunctions, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", 2); TryAdd("System.Data.Entity.DbFunctions, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", 2); TryAdd("System.Data.Entity.Spatial.DbGeography, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", 2); TryAdd("System.Data.Entity.SqlServer.SqlFunctions, EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", 2); TryAdd("System.Data.Entity.SqlServer.SqlSpatialFunctions, EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", 2); } #endif #if NETSTANDARD2_0_OR_GREATER || NET5_0_OR_GREATER const string publicKeyToken = "974e7e1b462f3693"; var version = Text.RegularExpressions.Regex.Match(typeof(PredefinedTypesHelper).AssemblyQualifiedName!, @"\d+\.\d+\.\d+\.\d+").ToString(); if (Type.GetType($"Microsoft.EntityFrameworkCore.DynamicLinq.EFType, Microsoft.EntityFrameworkCore.DynamicLinq, Version={version}, Culture=neutral, PublicKeyToken={publicKeyToken}") != null) { TryAdd($"Microsoft.EntityFrameworkCore.DynamicLinq.DynamicFunctions, Microsoft.EntityFrameworkCore.DynamicLinq, Version={version}, Culture=neutral, PublicKeyToken={publicKeyToken}", 3); } #endif } private static void TryAdd(string typeName, int x) { try { var type = Type.GetType(typeName); if (type != null) { PredefinedTypes.Add(type, x); } } catch { // In case of exception, do not add } } public static bool IsPredefinedType(ParsingConfig config, Type type) { Check.NotNull(config); Check.NotNull(type); var nonNullableType = TypeHelper.GetNonNullableType(type); if (PredefinedTypes.ContainsKey(nonNullableType)) { return true; } return config.CustomTypeProvider != null && (config.CustomTypeProvider.GetCustomTypes().Contains(type) || config.CustomTypeProvider.GetCustomTypes().Contains(nonNullableType)); } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/PredefinedTypesHelper.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
1,237
```smalltalk using System.Linq.Expressions; namespace System.Linq.Dynamic.Core.Parser { /// <summary> /// Expression promoter is used to promote object or value types /// to their destination type when an automatic promotion is available /// such as: int to int? /// </summary> public interface IExpressionPromoter { /// <summary> /// Promote an expression /// </summary> /// <param name="expr">Source expression</param> /// <param name="type">Destination data type to promote</param> /// <param name="exact">If the match must be exact</param> /// <param name="convertExpr">Convert expression</param> /// <returns>The promoted <see cref="Expression"/> or null.</returns> Expression? Promote(Expression expr, Type type, bool exact, bool convertExpr); } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/IExpressionPromoter.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
184
```smalltalk using System.Linq.Expressions; namespace System.Linq.Dynamic.Core.Parser; internal static class Constants { public static bool IsNull(Expression exp) { return exp is ConstantExpression { Value: null }; } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/Constants.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
44
```smalltalk using System.Diagnostics.CodeAnalysis; using System.Linq.Dynamic.Core.Util.Cache; using System.Linq.Dynamic.Core.Validation; using System.Linq.Expressions; namespace System.Linq.Dynamic.Core.Parser; internal class ConstantExpressionHelper { private readonly SlidingCache<object, Expression> _expressions; private readonly SlidingCache<Expression, string> _literals; public ConstantExpressionHelper(ParsingConfig config) { var parsingConfig = Check.NotNull(config); var cacheConfig = parsingConfig.ConstantExpressionCacheConfig ?? new CacheConfig(); _literals = new SlidingCache<Expression, string>(cacheConfig); _expressions = new SlidingCache<object, Expression>(cacheConfig); } public bool TryGetText(Expression expression, [NotNullWhen(true)] out string? text) { return _literals.TryGetValue(expression, out text); } public Expression CreateLiteral(object value, string text) { if (_expressions.TryGetValue(value, out var outputValue)) { return outputValue; } var constantExpression = Expression.Constant(value); _expressions.AddOrUpdate(value, constantExpression); _literals.AddOrUpdate(constantExpression, text); return constantExpression; } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/ConstantExpressionHelper.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
248
```smalltalk using System.Globalization; using System.Linq.Dynamic.Core.Exceptions; using System.Text.RegularExpressions; namespace System.Linq.Dynamic.Core.Parser; /// <summary> /// Parse a Double and Single Quoted string. /// Some parts of the code is based on path_to_url /// </summary> internal static class StringParser { private const string TwoDoubleQuotes = "\"\""; private const string SingleDoubleQuote = "\""; internal static string ParseStringAndUnescape(string s, int pos = default) { if (s == null || s.Length < 2) { throw new ParseException(string.Format(CultureInfo.CurrentCulture, Res.InvalidStringLength, s, 2), pos); } if (s[0] != '"' && s[0] != '\'') { throw new ParseException(string.Format(CultureInfo.CurrentCulture, Res.InvalidStringQuoteCharacter), pos); } char quote = s[0]; // This can be single or a double quote if (s.Last() != quote) { throw new ParseException(string.Format(CultureInfo.CurrentCulture, Res.UnexpectedUnclosedString, s.Length, s), pos); } try { return Regex.Unescape(s.Substring(1, s.Length - 2)); } catch (Exception ex) { throw new ParseException(ex.Message, pos, ex); } } internal static string ParseStringAndUnescapeTwoDoubleQuotesByASingleDoubleQuote(string input, int position = default) { return ReplaceTwoDoubleQuotesByASingleDoubleQuote(ParseStringAndUnescape(input, position), position); } private static string ReplaceTwoDoubleQuotesByASingleDoubleQuote(string input, int position) { try { return Regex.Replace(input, TwoDoubleQuotes, SingleDoubleQuote); } catch (Exception ex) { throw new ParseException(ex.Message, position, ex); } } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/StringParser.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
393
```smalltalk using System.Collections.Generic; namespace System.Linq.Dynamic.Core.Parser; internal class WrappedValue<TValue> { public TValue Value { get; } public WrappedValue(TValue value) { Value = value; } public static bool operator ==(WrappedValue<TValue>? left, WrappedValue<TValue>? right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } return EqualityComparer<TValue>.Default.Equals(left.Value, right.Value); } public static bool operator !=(WrappedValue<TValue>? left, WrappedValue<TValue>? right) { return !(left == right); } public static bool operator ==(WrappedValue<TValue>? left, TValue? right) { if (ReferenceEquals(left, null)) { return false; } return EqualityComparer<TValue>.Default.Equals(left.Value, right); } public static bool operator !=(WrappedValue<TValue>? left, TValue? right) { return !(left == right); } public static bool operator ==(TValue? left, WrappedValue<TValue>? right) { if (ReferenceEquals(right, null)) { return false; } return EqualityComparer<TValue>.Default.Equals(left, right.Value); } public static bool operator !=(TValue? left, WrappedValue<TValue>? right) { return !(left == right); } public override bool Equals(object? obj) { if (ReferenceEquals(this, obj)) { return true; } if (obj is not WrappedValue<TValue> other) { return false; } return EqualityComparer<TValue>.Default.Equals(Value, other.Value); } public override int GetHashCode() { return Value?.GetHashCode() ?? 0; } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/WrappedValue.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
409
```smalltalk using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; namespace System.Linq.Dynamic.Core.Parser; internal interface IConstantExpressionWrapper { void Wrap(ref Expression expression); bool TryUnwrapAsValue<TValue>(MemberExpression? expression, [NotNullWhen(true)] out TValue? value); bool TryUnwrapAsConstantExpression<TValue>(MemberExpression? expression, [NotNullWhen(true)] out ConstantExpression? value); } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/IConstantExpressionWrapper.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
86
```smalltalk namespace System.Linq.Dynamic.Core.Parser.SupportedOperands; internal interface ISubtractSignatures : IAddSignatures { void F(DateTime x, DateTime y); void F(DateTime x, DateTime? y); void F(DateTime? x, DateTime y); void F(DateTime? x, DateTime? y); } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/SupportedOperands/ISubtractSignatures.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
68
```smalltalk namespace System.Linq.Dynamic.Core.Parser.SupportedOperands; internal interface IArithmeticSignatures { void F(int x, int y); void F(uint x, uint y); void F(long x, long y); void F(ulong x, ulong y); void F(float x, float y); void F(double x, double y); void F(decimal x, decimal y); void F(int? x, int? y); void F(uint? x, uint? y); void F(long? x, long? y); void F(ulong? x, ulong? y); void F(float? x, float? y); void F(double? x, double? y); void F(decimal? x, decimal? y); } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/SupportedOperands/IArithmeticSignatures.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
164
```smalltalk namespace System.Linq.Dynamic.Core.Parser.SupportedOperands; internal interface IAddSignatures : IArithmeticSignatures { void F(TimeSpan x, TimeSpan y); void F(TimeSpan x, TimeSpan? y); void F(TimeSpan? x, TimeSpan y); void F(TimeSpan? x, TimeSpan? y); void F(DateTime x, TimeSpan y); void F(DateTime x, TimeSpan? y); void F(DateTime? x, TimeSpan y); void F(DateTime? x, TimeSpan? y); } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/SupportedOperands/IAddSignatures.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
107
```smalltalk namespace System.Linq.Dynamic.Core.Parser.SupportedOperands { internal interface IShiftSignatures { void F(int x, int y); void F(uint x, int y); void F(long x, int y); void F(ulong x, int y); void F(int? x, int y); void F(uint? x, int y); void F(long? x, int y); void F(ulong? x, int y); void F(int x, int? y); void F(uint x, int? y); void F(long x, int? y); void F(ulong x, int? y); void F(int? x, int? y); void F(uint? x, int? y); void F(long? x, int? y); void F(ulong? x, int? y); } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/SupportedOperands/IShiftSignatures.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
190
```smalltalk namespace System.Linq.Dynamic.Core.Parser.SupportedOperands { internal interface ILogicalSignatures { void F(bool x, bool y); void F(bool? x, bool? y); } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/SupportedOperands/ILogicalSignatures.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
46
```smalltalk namespace System.Linq.Dynamic.Core.Parser.SupportedOperands; internal interface IRelationalSignatures : IArithmeticSignatures { void F(string x, string y); void F(char x, char y); void F(DateTime x, DateTime y); void F(DateTimeOffset x, DateTimeOffset y); void F(TimeSpan x, TimeSpan y); void F(char? x, char? y); void F(DateTime? x, DateTime? y); void F(DateTimeOffset? x, DateTimeOffset? y); void F(TimeSpan? x, TimeSpan? y); #if NET6_0_OR_GREATER void F(DateOnly x, DateOnly y); void F(DateOnly? x, DateOnly? y); void F(TimeOnly x, TimeOnly y); void F(TimeOnly? x, TimeOnly? y); #endif } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/SupportedOperands/IRelationalSignatures.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
178
```smalltalk namespace System.Linq.Dynamic.Core.Parser.SupportedOperands { internal interface INegationSignatures { void F(int x); void F(long x); void F(float x); void F(double x); void F(decimal x); void F(int? x); void F(long? x); void F(float? x); void F(double? x); void F(decimal? x); } } ```
/content/code_sandbox/src/System.Linq.Dynamic.Core/Parser/SupportedOperands/INegationSignatures.cs
smalltalk
2016-04-08T16:41:51
2024-08-16T05:55:59
System.Linq.Dynamic.Core
zzzprojects/System.Linq.Dynamic.Core
1,537
92