LINQ

How to sanitize a file name using LINQ

From this article you can learn how to sanitize a file name using simple LINQ query. SanitizeFilename function takes two parameters:
  • name - filename that needs to be sanitized
  • replaceChar - char used to replace all invalid file name characters
Implementation is available both in C# and VB.Net languages. Use buttons below to switch language visibility.

Implementation

System.Linq namespace needs to be put in usings.

public static string SanitizeFileName(string name, char replaceChar)
{
  return Path.GetInvalidFileNameChars().Aggregate(name, (current, c) => current.Replace(c, replaceChar));
}
Public Shared Function SanitizeFileName(name As String, replaceChar As Char) As String
  Return Path.GetInvalidFileNameChars().Aggregate(name, Function(current, c) current.Replace(c, replaceChar))
End Function

LINQ lambda expressions in universal generic equality comparer

Implementation

Below you can find implementation we use as universal equality comparer. Only lambda expressions as in LINQ queries are needed to measure items. Class LambdaComparer is generic, so you can use it on any type you want to.

LambdaComparer class

using System;
using System.Collections.Generic;
 
namespace Karmian.Framework.Helpers
{
    public class LambdaComparer<T> : IEqualityComparer<T>
    {
        public LambdaComparer(Func<T, T, bool> equals, Func<T, int> getHashCode)
        {
            _equals = equals;
            _getHashCode = getHashCode;
        }
 
        readonly Func<T, T, bool> _equals;
        public bool Equals(T x, T y)
        {
            return _equals(x, y);
        }
 
        readonly Func<T, int> _getHashCode;
        public int GetHashCode(T obj)
        {
            return _getHashCode(obj);
        }
    } 
}
Syndicate content