Skip to content

Instantly share code, notes, and snippets.

@explorer14
Last active July 19, 2021 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save explorer14/fe20f96082c7396c21aeca260f95307b to your computer and use it in GitHub Desktop.
Save explorer14/fe20f96082c7396c21aeca260f95307b to your computer and use it in GitHub Desktop.
var propertiesWithCollectionTypes =
new List<(IPropertySymbol Symbol, PropertyDeclarationSyntax Syntax)>();
// somewhere here I add the properties that are
// generic collection type with custom type args.
// other code removed for brevity
foreach (var propertyTuple in propertiesWithCollectionTypes)
{
var namedType = propertyTuple.Symbol.Type as INamedTypeSymbol;
codeBuilder.AppendLine($"\tpublic static class " +
$"EntityExtensions{Guid.NewGuid().ToString().Replace("-", string.Empty)}");
codeBuilder.AppendLine("\t{");
if (namedType?.IsGenericType ?? false)
{
codeBuilder.AppendLine($"\t\tpublic static " +
$"{namedType.BuildDtoTypeWithGenericTypeArgs(propertyTuple.Syntax, propertyTuple.Symbol)} " +
$"ToDto(this {namedType.Name()} entities)");
if (namedType.IsDictionary())
{
codeBuilder.AppendLine("\t\t{");
codeBuilder.AppendLine($"\t\t\t if (entities == null) " +
$"return new {namedType.BuildDtoTypeWithGenericTypeArgs(propertyTuple.Syntax, propertyTuple.Symbol)}();");
codeBuilder.AppendLine("\t\t\t return null; //🤷‍♂️");
codeBuilder.AppendLine("\t\t}");
}
else
{
codeBuilder.AppendLine("\t\t{");
codeBuilder.AppendLine($"\t\t\t if (entities == null) " +
$"return Array.Empty<" +
$"{namedType.TypeArguments.First().Name}Dto>();");
codeBuilder.AppendLine("\t\t\t return entities.Select(x => x.ToDto()).ToList();");
codeBuilder.AppendLine("\t\t}");
}
}
else
{
codeBuilder.AppendLine($"\t\tpublic static " +
$"{propertyTuple.Symbol.Type.Name().Replace("[]", string.Empty)}Dto[] " +
$"ToDto(this {propertyTuple.Symbol.Type.Name()} entities)");
codeBuilder.AppendLine("\t\t{");
codeBuilder.AppendLine($"\t\t\t if (entities == null) " +
$"return Array.Empty<" +
$"{propertyTuple.Symbol.Type.Name().Replace("[]", string.Empty)}Dto>();");
codeBuilder.AppendLine("\t\t\t return entities.Select(x => x.ToDto()).ToArray();");
codeBuilder.AppendLine("\t\t}");
}
codeBuilder.AppendLine("\t}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment