Skip to main content

rscg_queryables by Andrei Ignat

Nuget / site data

NugetNuget GitHub last commit GitHub Repo stars

Details

Info

Original Readme

note

rscg_queryables

NuGet NuGet GitHub Actions

rscg_queryables is a Roslyn Code Generator designed to generate extension methods for sorting and filtering IEnumerable and IQueryable collections based on a given class.

Sorting how the user wants in frontend - description

Consider a scenario where we need to display a list of Person objects and allow the user to sort them by various properties. The user should have the ability to select the property and the sorting order.

public class Person
{
public string FirstName { get; set; } = string.Empty;
public string LastName { get; set; } = string.Empty;

public int Age { get; set; }
public string FullName
{
get
{
return $"{FirstName} {LastName}";
}
}
}

When data is transmitted over HTTP, it is often in the form of a string object. To sort by first name in descending order, the query string should look like this:

orderBy=FirstName&Asc=false

Then in the backend code we should parse the query string and apply the sorting logic.

if(queryString.ContainsKey("orderBy"))
{
string orderBy = queryString["orderBy"];
bool asc = queryString["asc"] == "false" ? false: true;//default is true
if(orderBy == "FirstName")
{
if(asc)
{
persons = persons.OrderBy(p => p.FirstName);
}
else
{
persons = persons.OrderByDescending(p => p.FirstName);
}
}
//do the same for other properties : LastName, Age, FullName

}

The solution

With rscg_queryables, you can do this in a more elegant way.

if(queryString.ContainsKey("orderBy"))
{
string orderBy = queryString["orderBy"];
bool asc = queryString["asc"] == "false" ? false: true;//default is true
persons = persons.OrderByAscDesc(orderBy, asc);
//or you can do this, if you want to control
//if(asc)
//{
// persons = persons.OrderBy(orderBy);
//}
//else
//{
// persons = persons.OrderByDescending(orderBy);
//}
}

This should be done for everything that implements IEnumerable or IQueryable.

Filtering Based on User Preferences - Description

Consider a scenario where we need to display a list of Person objects and allow the user to filter them by various properties. The user should have the ability to select the property, the filter criteria, and the filter operator (equal or different).

When data is transmitted over HTTP, it is often in the form of a string object. To filter by first name where the value is "John", the query string should look like this:

filterBy=FirstName&filterOperator=equal&filterValue=John

In the backend code, we need to parse the query string and apply the appropriate filtering logic.

if (queryString.ContainsKey("filterBy") && queryString.ContainsKey("filterOperator") && queryString.ContainsKey("filterValue"))
{
string filterBy = queryString["filterBy"];
string filterOperator = queryString["filterOperator"];
string filterValue = queryString["filterValue"];
if (filterBy == "FirstName")
{
if (filterOperator == "equal")
{
persons = persons.Where(p => p.FirstName == filterValue);
}
else if (filterOperator == "different")
{
persons = persons.Where(p => p.FirstName != filterValue);
}
}
// Do the same for other properties: LastName, Age, FullName
}

The Solution

With rscg_queryables, you can achieve this in a more elegant and efficient manner.

  1. add the nugets to your project
    <ItemGroup>
<PackageReference Include="rscg_queryablesCommon" Version="2024.1110.1815" />
<PackageReference Include="rscg_queryables" Version="2024.1110.1815" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>

Optional see the code generated

    <PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
</PropertyGroup>
  1. Modify the Person class to add the rscg_queryables attribute.
[MakeSortable]
[MakeWhere]
public class Person
{
//same code as above, omitted for brevity
}
  1. Use the overloaded Where method to filter the collection based on the query string.
if (queryString.ContainsKey("filterBy") && queryString.ContainsKey("filterOperator") && queryString.ContainsKey("filterValue"))
{
string filterBy = queryString["filterBy"];
string filterOperator = queryString["filterOperator"] == "equal"?WhereOperator.Equal:WhereOperator.Different;
string filterValue = queryString["filterValue"];
persons = persons.Where(filterBy, filterOperator, filterValue);

}

This approach can be applied to any collection that implements IEnumerable or IQueryable.

Other Roslyn Code Generators

For more Roslyn Source Code Generators, visit RSCG Examples https://ignatandrei.github.io/RSCG_Examples/v2/docs/rscg-examples.

About

note

Generating code for .Where and .OrderBy by string, not by lambda

How to use

Example ( source csproj, source files )

This is the CSharp Project that references rscg_queryables

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="rscg_queryablesCommon" Version="2024.1110.1815" />
<PackageReference Include="rscg_queryables" Version="2024.1110.1815" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>
<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
</PropertyGroup>
</Project>

Generated Files

Those are taken from $(BaseIntermediateOutputPath)\GX


public static partial class ExtensionsSortable_SortAndWhere_Student {

#region Enumerable
public static System.Linq.IOrderedEnumerable<global::SortAndWhere.Student> OrderBy
(
this IEnumerable<global::SortAndWhere.Student>
source, string propertyName
)
{

return OrderByAscDesc(source,propertyName,true);
}
public static System.Linq.IOrderedEnumerable<global::SortAndWhere.Student>
OrderByDescending
(
this IEnumerable<global::SortAndWhere.Student>
source, string propertyName
)
{

return OrderByAscDesc(source,propertyName,false);
}
public static System.Linq.IOrderedEnumerable<global::SortAndWhere.Student> OrderByAscDesc
(
this IEnumerable<global::SortAndWhere.Student> source, string propertyName, bool Ascending
)
{

if(string.Equals(propertyName, "FirstName", StringComparison.OrdinalIgnoreCase)){
if(Ascending)
return source.OrderBy(x => x.FirstName);
else
return source.OrderByDescending(x => x.FirstName);
}

if(string.Equals(propertyName, "LastName", StringComparison.OrdinalIgnoreCase)){
if(Ascending)
return source.OrderBy(x => x.LastName);
else
return source.OrderByDescending(x => x.LastName);
}

if(string.Equals(propertyName, "StartYear", StringComparison.OrdinalIgnoreCase)){
if(Ascending)
return source.OrderBy(x => x.StartYear);
else
return source.OrderByDescending(x => x.StartYear);
}
throw new ArgumentException($"Property {propertyName} not found", propertyName);
}

public static System.Linq.IOrderedEnumerable<global::SortAndWhere.Student> ThenByAscDesc
(
this IOrderedEnumerable<global::SortAndWhere.Student> source, string propertyName, bool Ascending
)
{

if(string.Equals(propertyName, "FirstName", StringComparison.OrdinalIgnoreCase)){
if(Ascending)
return source.ThenBy(x => x.FirstName);
else
return source.ThenByDescending(x => x.FirstName);
}

if(string.Equals(propertyName, "LastName", StringComparison.OrdinalIgnoreCase)){
if(Ascending)
return source.ThenBy(x => x.LastName);
else
return source.ThenByDescending(x => x.LastName);
}

if(string.Equals(propertyName, "StartYear", StringComparison.OrdinalIgnoreCase)){
if(Ascending)
return source.ThenBy(x => x.StartYear);
else
return source.ThenByDescending(x => x.StartYear);
}
throw new ArgumentException($"Property {propertyName} not found", propertyName);
}
public static System.Linq.IOrderedEnumerable<global::SortAndWhere.Student> ThenBy
(
this IOrderedEnumerable<global::SortAndWhere.Student>
source, string propertyName
)
{

return ThenByAscDesc(source,propertyName,true);
}
public static System.Linq.IOrderedEnumerable<global::SortAndWhere.Student> ThenByDescending
(
this IOrderedEnumerable<global::SortAndWhere.Student>
source, string propertyName
)
{

return ThenByAscDesc(source,propertyName,false);
}

#endregion

#region Queryable
public static System.Linq.IOrderedQueryable<global::SortAndWhere.Student> OrderBy
(
this IQueryable<global::SortAndWhere.Student>
source, string propertyName
)
{

return OrderByAscDesc(source,propertyName,true);
}
public static System.Linq.IOrderedQueryable<global::SortAndWhere.Student>
OrderByDescending
(
this IQueryable<global::SortAndWhere.Student>
source, string propertyName
)
{

return OrderByAscDesc(source,propertyName,false);
}
public static System.Linq.IOrderedQueryable<global::SortAndWhere.Student> OrderByAscDesc
(
this IQueryable<global::SortAndWhere.Student> source, string propertyName, bool Ascending
)
{

if(string.Equals(propertyName, "FirstName", StringComparison.OrdinalIgnoreCase)){
if(Ascending)
return source.OrderBy(x => x.FirstName);
else
return source.OrderByDescending(x => x.FirstName);
}

if(string.Equals(propertyName, "LastName", StringComparison.OrdinalIgnoreCase)){
if(Ascending)
return source.OrderBy(x => x.LastName);
else
return source.OrderByDescending(x => x.LastName);
}

if(string.Equals(propertyName, "StartYear", StringComparison.OrdinalIgnoreCase)){
if(Ascending)
return source.OrderBy(x => x.StartYear);
else
return source.OrderByDescending(x => x.StartYear);
}
throw new ArgumentException($"Property {propertyName} not found", propertyName);
}
public static System.Linq.IOrderedQueryable<global::SortAndWhere.Student> ThenByAscDesc
(
this IOrderedQueryable<global::SortAndWhere.Student> source, string propertyName, bool Ascending
)
{

if(string.Equals(propertyName, "FirstName", StringComparison.OrdinalIgnoreCase)){
if(Ascending)
return source.ThenBy(x => x.FirstName);
else
return source.ThenByDescending(x => x.FirstName);
}

if(string.Equals(propertyName, "LastName", StringComparison.OrdinalIgnoreCase)){
if(Ascending)
return source.ThenBy(x => x.LastName);
else
return source.ThenByDescending(x => x.LastName);
}

if(string.Equals(propertyName, "StartYear", StringComparison.OrdinalIgnoreCase)){
if(Ascending)
return source.ThenBy(x => x.StartYear);
else
return source.ThenByDescending(x => x.StartYear);
}
throw new ArgumentException($"Property {propertyName} not found", propertyName);
}
public static System.Linq.IOrderedQueryable<global::SortAndWhere.Student> ThenBy
(
this IOrderedQueryable<global::SortAndWhere.Student>
source, string propertyName
)
{

return ThenByAscDesc(source,propertyName,true);
}
public static System.Linq.IOrderedQueryable<global::SortAndWhere.Student> ThenByDescending
(
this IOrderedQueryable<global::SortAndWhere.Student>
source, string propertyName
)
{

return ThenByAscDesc(source,propertyName,false);
}

#endregion

}

Usefull

Download Example (.NET C# )

Share rscg_queryables

https://ignatandrei.github.io/RSCG_Examples/v2/docs/rscg_queryables

In the same category (FunctionalProgramming) - 14 other generators

cachesourcegenerator

dunet

Dusharp

Funcky.DiscriminatedUnion

FunicularSwitch

N.SourceGenerators.UnionTypes

OneOf

PartiallyApplied

polytype

RSCG_Utils_Memo

Sera.Union

TypeUtilities

UnionGen

UnionsGenerator