Last active
August 31, 2016 08:14
-
-
Save ryanlewis/ad28c52bc31aa5e32647 to your computer and use it in GitHub Desktop.
.FormatWith() extension method that we use with some of our Umbraco sites
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Text.RegularExpressions; | |
using System.Web; | |
namespace MyUmbracoSite.Core.Extensions | |
{ | |
public static class StringExtensions | |
{ | |
// http://bendetat.com/the-greatest-string-formatwith-implementation-in-the-world.html | |
public static string FormatWith(this string format, params object[] args) | |
{ | |
if (format == String.Empty) return format; | |
args = args ?? new object[0]; | |
string result; | |
var numberedTemplateCount = (from object match in new Regex(@"\{\d{1,2}\}").Matches(format) select match.ToString()).Distinct().Count(); | |
if (numberedTemplateCount != args.Length) | |
{ | |
var argsDictionary = args[0].ToDictionary(); | |
if (!argsDictionary.Any()) | |
{ | |
throw new InvalidOperationException("Please supply enough args for the numbered templates or use an anonymous object to identify the templates by name."); | |
} | |
result = argsDictionary.Aggregate(format, (current, o) => current.Replace("{" + o.Key + "}", (o.Value ?? string.Empty).ToString())); | |
} | |
else | |
{ | |
result = string.Format(format, args); | |
} | |
if (result == format && result.Contains("{")) | |
{ | |
throw new InvalidOperationException("You cannot mix template types. Use numbered templates or named ones with an anonymous object."); | |
} | |
return result; | |
} | |
} | |
} |
Author
ryanlewis
commented
Aug 31, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment