using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using JD.Kernel.StaticHelpers;
namespace JD.Collections.Utilities
{
///
/// Used to get a string representation of the elements in a collection.
/// Each item in the collection is converted to a string by calling its
/// ToString method (null is represented by "null").
///
public class CollectionPrinter
{
#region Constants
private const string NullString = "null";
#endregion
#region Variables
private bool m_recursive = true;
private string m_startToken = "{";
private string m_endToken = "}";
private string m_separator = ", ";
#endregion
#region Properties
///
/// If true, contained collections (except strings) are converted to strings by a
/// recursive call to the printer, instead of calling ToString.
///
public bool Recursive
{
get { return m_recursive; }
set
{
m_recursive = value;
}
}
///
/// The string that delimits the beginning of the output string.
///
public string StartToken
{
get { return m_startToken; }
set
{
Throw.IfEmpty(value, "StartToken");
m_startToken = value;
}
}
///
/// The string that delimits the end of the output string.
///
public string EndToken
{
get { return m_endToken; }
set
{
Throw.IfEmpty(value, "EndToken");
m_endToken = value;
}
}
///
/// The string that delimits each item in the collection.
///
public string Separator
{
get { return m_separator; }
set
{
Throw.IfEmpty(value, "Separator");
m_separator = value;
}
}
#endregion
#region Methods
public string Print(IEnumerable collection)
{
if (collection == null)
{
return NullString;
}
StringBuilder builder = new StringBuilder();
builder.Append(StartToken);
PrintCollection(builder, collection);
builder.Append(EndToken);
return builder.ToString();
}
private void PrintCollection(StringBuilder builder, IEnumerable collection)
{
bool firstItem = true;
foreach (object item in collection)
{
if (!firstItem)
{
builder.Append(Separator);
}
firstItem = false;
PrintObject(builder, item);
}
}
private void PrintObject(StringBuilder builder, object item)
{
if (ReferenceEquals(item, null))
{
builder.Append(NullString);
}
else if (Recursive && item.GetType().IsGenericType && item.GetType().GetGenericTypeDefinition() == typeof(KeyValuePair<,>))
{
Type itemType = item.GetType();
object key = itemType.GetProperty("Key").GetValue(item, null);
object value = itemType.GetProperty("Value").GetValue(item, null);
PrintObject(builder, key);
builder.Append(" = ");
PrintObject(builder, value);
}
else if (Recursive && item is IEnumerable && !(item is string))
{
builder.Append(Print((IEnumerable)item));
}
else if (item is IFormattable)
{
builder.Append(((IFormattable)item).ToString(string.Empty, System.Globalization.CultureInfo.InvariantCulture));
}
else
{
builder.Append(item);
}
}
#endregion
}
}