Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The key is you want to keep a <code>Stack</code> of the current property while you recursively search for the value you're after and also a <code>HashSet</code> of visited objects and skip them. You also want to be careful with your exception handling so an exception in the middle doesn't mess up the stack.</p> <pre><code> public static string[] FindPathToProperty(object item, string propertyValueToFind) { var pathToProperty = new Stack&lt;string&gt;(); var visitedObjects = new HashSet&lt;object&gt; {item}; FindPathToProperty(item, propertyValueToFind, pathToProperty, visitedObjects); var finalPath = pathToProperty.ToArray(); Array.Reverse(finalPath); return finalPath; } private static bool FindPathToProperty(object item, string propertyValueToFind, Stack&lt;string&gt; pathToProperty, HashSet&lt;object&gt; visitedObjects) { foreach (var property in item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { try { var value = property.GetValue(item, null); if (visitedObjects.Contains(value)) { continue; } visitedObjects.Add(value); pathToProperty.Push(property.Name); bool found = false; try { found = propertyValueToFind.Equals(value) || FindPathToProperty(value, propertyValueToFind, pathToProperty, visitedObjects); } finally { if (!found) { pathToProperty.Pop(); } } if (found) { return true; } } catch { continue; } } return false; } public static void Test() { Test(new { X = "find" }, "X"); Test(new { X = "no", Y = "find" }, "Y"); Test(new { A = new { X = "no", Y = "find" } }, "A.Y"); } private static void Test(object item, string expected) { string actual = string.Join(".", FindPathToProperty(item, "find")); Console.WriteLine("{0} : {1}\r\n {2}", actual == expected ? "ok " : "BAD", expected, actual); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload