Skip to content

Instantly share code, notes, and snippets.

@jchandra74
Created September 7, 2016 03:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jchandra74/004e3328da353895ebbe381ad46f156b to your computer and use it in GitHub Desktop.
Save jchandra74/004e3328da353895ebbe381ad46f156b to your computer and use it in GitHub Desktop.
Object graph walker that will clean up empty array, generic collection and string
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Foo
{
public static class ObjectExtensions
{
public static void NullifyEmptyProperties(this object o)
{
if (o == null) return;
var t = o.GetType();
var props = t.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.DeclaredOnly);
foreach (var p in props)
{
var propType = p.PropertyType;
if (propType.IsArray)
{
var a = (Array)p.GetValue(o);
if (a.Length == 0)
{
p.SetValue(o, null);
continue;
}
for (var i = 0; i < a.Length; i++)
{
var item = a.GetValue(i);
var s1 = item as string;
if (s1 != null)
{
var s = s1;
if (string.IsNullOrEmpty(s))
{
a.SetValue(null, i);
continue;
}
}
NullifyEmptyProperties(item);
}
continue;
}
if (propType.IsGenericType)
{
var g = p.GetValue(o);
var al = (int)propType.GetProperty("Count").GetValue(g);
if (al == 0)
{
p.SetValue(o, null);
continue;
}
for (var i = 0; i < al; i++)
{
var item = propType.GetMethod("get_Item").Invoke(g, new object[] { i });
var s1 = item as string;
if (s1 != null)
{
var s = s1;
if (string.IsNullOrEmpty(s))
{
propType.GetMethod("set_Item").Invoke(g, new object[] {i, null});
continue;
}
}
NullifyEmptyProperties(item);
}
continue;
}
if (propType.IsPrimitive)
{
continue;
}
if (propType.IsValueType)
{
continue;
}
if (propType == typeof(string))
{
var s = (string) p.GetValue(o);
if (string.IsNullOrEmpty(s))
{
p.SetValue(o, null);
continue;
}
}
var v = p.GetValue(o);
NullifyEmptyProperties(v);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment