Created
September 4, 2019 04:43
-
-
Save mamift/f94ee2aece832e83141bd1f583db9699 to your computer and use it in GitHub Desktop.
Extension methods that converts a sequence (IEnumerable<>) of objects to a delimited string. Includes a generic method.
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
public static class ExtensionMethods | |
{ | |
/// <summary> | |
/// Converts an <see cref="IEnumerable{T}"/> of <see cref="string"/>s to a flat string, delimited by a delimiter string. | |
/// </summary> | |
/// <param name="stringEnumerable"></param> | |
/// <param name="delimiter">Defaults to comma with a space (, )</param> | |
/// <param name="openEncloseString">Enclose each string in the IEnumerable inside two other strings. e.g. an apostrophe will produce: ('a', 'b', 'c')</param> | |
/// <param name="closeEncloseString"></param> | |
/// <returns></returns> | |
public static string ToDelimitedString(this IEnumerable<string> stringEnumerable, string delimiter = ", ", string openEncloseString = "", string closeEncloseString = "") | |
{ | |
var result = ""; | |
var enumerable = stringEnumerable as string[] ?? stringEnumerable.ToArray(); | |
var lastIndex = enumerable.Length - 1; | |
for (var i = 0; i < enumerable.Length; i++) | |
{ | |
var individualString = enumerable.ElementAt(i); | |
// enclose each string if need be | |
if (!string.IsNullOrWhiteSpace(openEncloseString)) individualString = $"{openEncloseString}{individualString}{closeEncloseString}"; | |
// dont add the delimiter to the very last one | |
if (i != lastIndex) | |
result = result + $"{individualString}{delimiter}"; | |
else | |
result = result + individualString; | |
} | |
return result; | |
} | |
/// <summary> | |
/// Generic wrapper method for <see cref="ToDelimitedString"/>. Invokes the <see cref="object.ToString"/> method on each element in the sequence. | |
/// </summary> | |
/// <typeparam name="TType"></typeparam> | |
/// <param name="theEnumerableOfThings"></param> | |
/// <param name="delimiter"></param> | |
/// <param name="openEncloseString"></param> | |
/// <param name="closeEncloseString"></param> | |
/// <returns></returns> | |
public static string ToDelimitedString<TType>(this IEnumerable<TType> theEnumerableOfThings, string delimiter = ", ", string openEncloseString = "", | |
string closeEncloseString = "") | |
{ | |
var castedEnumerable = theEnumerableOfThings.Select(thing => thing.ToString()); | |
return castedEnumerable.ToDelimitedString(delimiter, openEncloseString, closeEncloseString); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment