mo.*_*mo. 2 .net c# recursion conditional
什么是打破循环的最佳做法?我的想法是:
Child Find(Parent parent, object criteria)
{
Child child = null;
foreach(Child wannabe in parent.Childs)
{
if (wannabe.Match(criteria))
{
child = wannabe;
}
else
{
child = Find(wannabe, criteria);
}
if (child != null) break;
}
return child;
}
Run Code Online (Sandbox Code Playgroud)
要么
Child Find(Parent parent, object criteria)
{
Child child = null;
var conditionator = from c in parent.Childs where child != null select c;
foreach(Child wannabe in conditionator)
{
if (wannabe.Match(criteria))
{
child = wannabe;
}
else
{
child = Find(wannabe, criteria);
}
}
return child;
}
Run Code Online (Sandbox Code Playgroud)
要么
Child Find(Parent parent, object criteria)
{
Child child = null;
var enumerator = parent.Childs.GetEnumerator();
while(child != null && enumerator.MoveNext())
{
if (enumerator.Current.Match(criteria))
{
child = wannabe;
}
else
{
child = Find(wannabe, criteria);
}
}
return child;
}
Run Code Online (Sandbox Code Playgroud)
您认为什么,更好的想法?我正在寻找最有效的解决方案:D
莫
Linq可能更简洁,但可能更难理解!
Child Find(Parent parent, object criteria)
{
return parent.Childs.Select( // Loop through the children looking for those that match the following criteria
c => c.Match(criteria) // Does this child match the criteria?
? c // If so, just return this child
: this.Find(c, criteria) // If not, try to find it in this child's children
).FirstOrDefault(); // We're only interested in the first child that matches the criteria or null if none found
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
321 次 |
| 最近记录: |