Remove empty folders using PowerShell

 
 
  • Gérald Barré
Here's a PowerShell script that removes empty folders recursively: $rootFolder = 'C:\Temp' Get-ChildItem $rootFolder -Recurse -Directory -Force | Sort-Object -Property FullName -Descending | Where-Object { $($_ | Get-ChildItem -Force | Select-Object -First 1).Count -eq 0 } | Remove-Item The logic is following: Get all directories recursively, use -Force to get hidden folders Sort them in descending order… [read more]

How to use a natural sort in PowerShell

 
 
  • Gérald Barré
PowerShell doesn't provide a built-in way to use a natural sort. However, you can use the Sort-Object cmdlet with a custom script block to achieve a natural sort. In this post, I describe how you can use a natural sort in PowerShell. What is a natural sort? A natural sort is a sorting algorithm that orders strings in a way that is more human-friendly. For example, a natural sort of the following strings:… [read more]

static lambda functions are not static methods

 
 
  • Gérald Barré
Stating with C# 9.0, you can use the static modifier on lambda functions. For instance, you can write the following code: enumerable.Select(static x => x * 2); When you use the static modifier on a lambda function, the compilers ensures that there is no capture of variables from the enclosing scope. This allows the compiler to generate better code. Indeed, it can cache the lambda function and reuse it… [read more]

How to iterate on a ConcurrentDictionary: foreach vs Keys/Values

 
 
  • Gérald Barré
There are multiple ways to iterate on a ConcurrentDictionary<TKey, TValue> in .NET. You can use the foreach loop, or the Keys and Values properties. Both methods provide different results, and you should choose the one that best fits your needs. Using the foreach loop The foreach loop lazily iterates over the key-value pairs in the ConcurrentDictionary. This means that the loop will only fetch the next… [read more]

How does the compiler infer the type of default?

 
 
  • Gérald Barré
The default keyword is a powerful tool in C#. For reference types, it returns null, and for value types (structs), it returns a zeroed-out value. Interestingly, default(T) and new T() can yield different results for structs (check out for more info). Initially, C# required default(T), but now you can simply use default when the type can be inferred by the compiler. But how does the compiler infer the… [read more]

Detect missing migrations in Entity Framework Core

 
 
  • Gérald Barré
Entity Framework Core allows to update the database schema using migrations. The migrations are created manually by running a CLI command. It's easy to forget to create a new migration when you change the model. To ensure the migrations are up-to-date, you can write a test that compares the current model with the snapshot model: [Fact] public async Task EnsureMigrationsAreUpToDate() { await using var… [read more]