Note that there are some explanatory texts on larger screens.

plurals
  1. POSearching Hierarchical List
    primarykey
    data
    text
    <p>I've got a simple class defined as:</p> <pre><code>public class IndexEntry { public bool HighScore { get; set; } public List&lt;IndexEntry&gt; SubEntries { get; set; } //Other properties, etc... } </code></pre> <p>I now need to search through a List to find the one item that has its HighScore Property set to <strong><em>true</em></strong>. Since it isn't a flat list, but a Hierarchy which can be an unknown number of levels deep and since the item I'm looking for might be contained in any one of the SubEnties lists, I can't do a simple Lambda like this:</p> <pre><code>var foundHighScore = myList.FirstOrDefault(IE =&gt; IE.HighScore == true); </code></pre> <p>Here's the code I have. I know it's ugly (at least it seems that way to me). It works, but is slow as sin on an even remotely large list and I'm sure there must be a better way.</p> <pre><code>private IndexEntry GetHighScoreEntry(IEnumerable&lt;IndexEntry&gt; entryList) { IndexEntry result = null; IndexEntry recursiveResult = null; foreach (IndexEntry currentEntry in entryList) { if (currentEntry.HighScore) { result = currentEntry; break; //Don't need to look anymore, we found our highscore.; } else { if ((currentEntry.SubEntries == null) || (currentEntry.SubEntries.Count &lt; 1)) { continue; } else { recursiveResult = GetHighScoreEntry(currentEntry.SubEntries); if (recursiveResult == null) continue; result = recursiveResult; break; } } } return result; } </code></pre> <p>I've got believe that there's a better way using a slightly more complex lambda or with LINQ to clean up this code and make it more performant.</p> <p>Thanks in advance for your help.</p>
    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.
 

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