打破循环的最佳做法是什么? 我的想法是:
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;
}
或
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;
}
或
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;
}
你觉得怎么样,有什么更好的主意吗? 我正在寻找最好的解决方案 :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
}
关于c# - 递归条件 - 最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2739337/