RSCG – TrimItEasy
| name | TrimItEasy |
| nuget | https://www.nuget.org/packages/TrimItEasy/ |
| link | https://github.com/phongnguyend/TrimItEasy |
| author | Phong Nguyen |
trimming eacg string from a class properties
This is how you can use TrimItEasy .
The code that you start with is
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="TrimItEasy" Version="1.0.0" />
<PackageReference Include="TrimItEasy.Generators" Version="1.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
</PropertyGroup>
</Project>
The code that you will use is
using TrimDemo; Person p = new(); p.FirstName = " Andrei "; p.LastName = " Ignat "; p.FastTrimStrings(); Console.WriteLine(p.FirstName + " " + p.LastName);
The code that is generated is
//
#nullable enable
using System.Collections;
using System.Collections.Generic;
namespace TrimDemo;
public static partial class PersonExtensions
{
public static partial void FastTrimStrings(this global::TrimDemo.Person person)
{
var visited = new HashSet
private static void TrimProperties_TrimDemo_Person(global::TrimDemo.Person obj, HashSet
if (obj.FirstName != null)
{
obj.FirstName = obj.FirstName.Trim();
}
if (obj.LastName != null)
{
obj.LastName = obj.LastName.Trim();
}
}
private static void TrimRecursive(object? obj, HashSet
var type = obj.GetType();
if (type.IsPrimitive || type.IsEnum || type == typeof(decimal) || type == typeof(System.DateTime) || type == typeof(System.DateTimeOffset))
{
return;
}
if (!type.IsValueType && !visited.Add(obj))
{
return;
}
if (obj is global::TrimDemo.Person typed_TrimDemo_Person)
{
TrimProperties_TrimDemo_Person(typed_TrimDemo_Person, visited);
return;
}
if (obj is IList list)
{
for (int i = 0; i < list.Count; i++)
{
if (list[i] is string s)
{
list[i] = s.Trim();
}
else
{
TrimRecursive(list[i], visited);
}
}
return;
}
if (obj is IEnumerable enumerable)
{
foreach (var item in enumerable)
{
if (item is not string)
{
TrimRecursive(item, visited);
}
}
return;
}
}
}
[/code]
Code and pdf at
https://ignatandrei.github.io/RSCG_Examples/v2/docs/TrimItEasy