I have a simple class that is defined as:
public class IndexEntry
{
public bool HighScore { get; set; }
public List<IndexEntry> SubEntries { get; set; }
}
Now I need to search the list to find one item that has its HighScore property set to true . Since this is not a flat list, but a hierarchy, which can be an unknown number of levels, and since the element I'm looking for can be contained in any of the SubEnties lists, I can not do this simple Lambda:
var foundHighScore = myList.FirstOrDefault(IE => IE.HighScore == true);
Here is the code I have. I know this is ugly (at least I think it is). It works, but more slowly than sin on an even remotely large list, and I'm sure there should be a better way.
private IndexEntry GetHighScoreEntry(IEnumerable<IndexEntry> entryList)
{
IndexEntry result = null;
IndexEntry recursiveResult = null;
foreach (IndexEntry currentEntry in entryList)
{
if (currentEntry.HighScore)
{
result = currentEntry;
break;
}
else
{
if ((currentEntry.SubEntries == null) || (currentEntry.SubEntries.Count < 1))
{
continue;
}
else
{
recursiveResult = GetHighScoreEntry(currentEntry.SubEntries);
if (recursiveResult == null)
continue;
result = recursiveResult;
break;
}
}
}
return result;
}
I find it better to use a slightly more complex lambda or LINQ to clear this code and make it more efficient.
Thanks in advance for your help.