string.Join Extension Method

April 19, 2018 .net c# linq

Normally if want to do a string.Join on the result of a Linq query you end up with somthing looking like this:

Console.WriteLine(string.Join(", ", numbers.Where(x => x % 2 == 0)));

The call to string.Join has to come first and then the Linq query. I've always felt this breaks the flow of the code and would be easier to read if the string.Join was at the end of the Linq query:

Console.WriteLine(numbers.Where(x => x % 2 == 0).JoinString(", "));

This can be implemented with the following extension methods:

public static class JoinStringExtensions
{
    public static string JoinString<T>(this IEnumerable<T> source, string seperator) =>
        string.Join(seperator, source.Select(x => x.ToString()));

    public static string JoinString(this IEnumerable<string> source, string seperator) =>
        string.Join(seperator, source);
}

The specialization for IEnumerable<string> is just mirroring the implementation from string.Join.

LINQ calls IEqualityComparer<T>.GetHashCode() before Equals()

November 24, 2014 .net linq

This is a problem that has bitten me more than a few times so I thought it was about time to write a blog post about it. It's one of those problems that makes you scratch your head for a bit and then the light bulb goes on and you remember you've solved this one before. It occurs whenever you use a LINQ extension method which takes an instance of IEqualityComaparer.

Read More