Wednesday, 24 August 2011

Nice LINQ Path.Combine trick

It’s a simple thing – but it’s a nice thing, instead of multiple explicit calls to Path.Combine:

using System;
using System.Linq;

namespace PathAggregation
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(
		AggregatePath("some", "interesting", "path")
            );
            
	    Console.ReadKey();
        }

        static string AggregatePath(params string[] pathParts)
        {
            return pathParts.Aggregate(System.IO.Path.Combine);
        }
    }
}

2 comments:

Chris Oldwood said...

C# 4 adds an overload of String.Join that takes an IEnumerable. Used with Path.PathSeparator you have another alternative.

Tim Barrass said...

Thanks for the pointer (suspect you meant Path.DirectorySeparatorChar?) I geuss we've had String.Join(string, string[]) from 2.0 or so, but IEnumerable sounds more useful.