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

ToSortedString

Returns an alphabetically sorted list for all public and instance properties, along with its associated values.

Source

public static string ToSortedString(this object value)
{
    BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public;
    SortedDictionary<string, string> values = new SortedDictionary<string, string>();

    PropertyInfo[] properties = value.GetType().GetProperties(bindingFlags);
    foreach (PropertyInfo property in properties)
    {
        string propertyName = property.Name;
        object propertyValue = property.GetValue(value, null);
        string maskedValue = propertyValue == null ? "null" : propertyValue.ToString();

        values.Add(propertyName, maskedValue);
    }

    StringBuilder sb = new StringBuilder();
    foreach (KeyValuePair<string, string> item in values)
    {
        sb.AppendFormat("{0}={1}{2}", item.Key, item.Value, Environment.NewLine);
    }

    return sb.ToString();
}

Example

MyClass c = new MyClass();
string data = c.ToSortedString();

Author: Alvaro Torres Tatis

Submitted on: 16 feb. 2012

Language: C#

Type: System.Object

Views: 4794