ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

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

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

Source

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();

Author: James Levingston

Submitted on: 19 okt. 2010

Language: C#

Type: System.Object

Views: 5900