StringComparison.InvariantCulture is not always invariant

 
 
  • Gérald Barré
CultureInfo.InvariantCulture is not invariant for all operations. It is a special culture that is used for formatting and parsing operations that do not depend on any specific culture. For instance, this is well-suited to format values in order to persist them. However, it is not invariant for string comparisons. Comparing strings using InvariantCulture can lead to different results depending on the… [read more]

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]