Skip to content

Instantly share code, notes, and snippets.

@yehudamakarov
Last active June 24, 2019 22:16
Show Gist options
  • Save yehudamakarov/5d48e6a01648d938f1c56514e9f693ac to your computer and use it in GitHub Desktop.
Save yehudamakarov/5d48e6a01648d938f1c56514e9f693ac to your computer and use it in GitHub Desktop.
[GetAllInstances] Gets a list of the specified type's values from an object.
public static List<T> GetAllInstances<T>(object value) where T : class
{
var exploredObjects = new HashSet<object>();
var found = new List<T>();
FindAllInstances(value, exploredObjects, found);
return found;
}
private static void FindAllInstances<T>(object value, ISet<object> exploredObjects, ICollection<T> found)
where T : class
{
if (value == null) return;
if (exploredObjects.Contains(value)) return;
exploredObjects.Add(value);
if (value is IEnumerable enumerable)
{
foreach (var item in enumerable)
{
FindAllInstances(item, exploredObjects, found);
}
}
else
{
if (value is T possibleMatch)
{
found.Add(possibleMatch);
}
var type = value.GetType();
var properties = type.GetProperties(
// BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty
);
foreach (var property in properties)
{
var propertyValue = property.GetValue(value, null);
FindAllInstances(propertyValue, exploredObjects, found);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment