using System.Collections.Generic;
public static void Main()
var simple = new HashSet<string>();
Console.WriteLine("Simple Before => " + JsonConvert.SerializeObject(simple));
simple = simple.DeepTrimAll();
Console.WriteLine("Simple After => " + JsonConvert.SerializeObject(simple));
var complex = new Complex();
complex.HS = new HashSet<string>();
Console.WriteLine("Complex Before => " + JsonConvert.SerializeObject(complex));
complex = complex.DeepTrimAll();
Console.WriteLine("Complex After => " + JsonConvert.SerializeObject(complex));
public HashSet<string> HS
public static T DeepTrimAll<T>(this T context, Type t)where T : class
if (context is IEnumerable<string>)
Console.WriteLine("T = " + type.ToString() + " , t = " + t.ToString());
var list = new List<string>(context as IEnumerable<string>);
for (int i = 0; i < list.Count(); i++)
list[i] = list[i].Trim();
var res = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(list), t);
var properties = typeof (T).GetProperties().Where(x => x.CanRead && x.CanWrite).ToList();
foreach (var propertyInfo in properties)
var propType = propertyInfo.PropertyType;
var value = propertyInfo.GetValue(context, null);
if (propType == typeof (string))
if (!string.IsNullOrWhiteSpace(value.ToString()))
propertyInfo.SetValue(context, value.ToString().Trim());
else if (!propType.IsEnum && !propType.IsPrimitive)
var newValue = value.DeepTrimAll(propType);
propertyInfo.SetValue(context, newValue);
public static T DeepTrimAll<T>(this T context)where T : class
return context.DeepTrimAll(typeof (T));