Created
March 4, 2019 21:31
-
-
Save pmunin/5e3057cbaf70954d89545ebcc80e5ee1 to your computer and use it in GitHub Desktop.
C# FormattableStringExtensions.cs
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.Collections.Generic; | |
using System.Linq; | |
using System.Runtime.CompilerServices; | |
using System.Threading.Tasks; | |
public static class FormattableStringExtensions | |
{ | |
public static FormattableString AsFormattable(this string str) { | |
return FormattableStringFactory.Create(str); | |
} | |
class FormattablePlaceholder : IFormattable | |
{ | |
public Func<string, IFormatProvider, string> ValueByFormat { get; set; } | |
public string ToString(string format, IFormatProvider formatProvider) | |
{ | |
return ValueByFormat(format, formatProvider); | |
} | |
} | |
public static FormattableString Join(string separator, params FormattableString[] strings) | |
{ | |
var iArg = 0; | |
var formats = strings.Select(str => | |
{ | |
var args = Enumerable.Range(iArg, str.ArgumentCount).ToArray(); | |
iArg += str.ArgumentCount; | |
return string.Format(str.Format, args: args.Select(arg=> new FormattablePlaceholder() { | |
ValueByFormat = (fmt, fp) => fmt != null ? $"{{{arg}}}:{fmt}}}" : $"{{{arg}}}" | |
}).ToArray()); | |
}).ToArray(); | |
return FormattableStringFactory.Create(string.Join(separator, value:formats), arguments: strings.SelectMany(s => s.GetArguments()).ToArray()); | |
} | |
public static FormattableString Add(this FormattableString formattable, params FormattableString[] strings) | |
{ | |
strings = new[] { formattable }.Concat(strings).ToArray(); | |
return Join(string.Empty,strings); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment