ToDelimitedString<T>(char delimiter, Func<T, PropertyInfo, string> func)

public static string ToDelimitedString<T>(this T obj, char delimiter, Func<T, System.Reflection.PropertyInfo, string> func)
        {
            if (obj == null || func == null)
                return null;

            var builder = new StringBuilder();
            var props = obj.GetType().GetProperties();
            for (int p = 0; p < props.Length; p++ )
                builder.Append(func(obj, props[p]) + delimiter.ToString());

            //Remove the last character, the last delimiter
            if (builder.Length > 0)
                return builder.ToString().Remove(builder.ToString().Length - 1);

            return null;
        }
Example:
--> Expand with more extensions

  public static string ToCommaDelimitedString(this object obj)
        {
            return obj.ToDelimitedString<object>(',',
                (object o, System.Reflection.PropertyInfo p) => { return (string.Format("{0}.{1}={2}", p.ReflectedType.Name, p.Name, Convert.ToString(p.GetValue(o, null)))); });
        }

        public static string ToPipeDelimitedString(this object obj)
        {
            return obj.ToDelimitedString<object>('|',
                (object o, System.Reflection.PropertyInfo p) => { return (string.Format("{0}.{1}={2}", p.ReflectedType.Name, p.Name, Convert.ToString(p.GetValue(o, null)))); });
        }

--> Above examples in use is below.

var commaLine = obj.ToCommaDelimitedString();
var pipeLine = obj.ToPipeDelimitedString();

Description

Map any object T to a delimited string and control how that string is formatted.

Details

Double click on the code to select all.

 

;