LINQ 和递归
请考虑以下问题:
public class Box
{
public BoxSize Size { get; set; }
public IEnumerable<Box> Contents { get; set; }
}
Box FindBoxBySize(Box box, BoxSize size)
{
Box _foundBox = null;
Action<IEnumerable<Box>> _recurse = null;
_recurse = new Action<IEnumerable<Box>>(boxes =>
{
foreach (var _box in boxes)
{
if (_box.Size == size)
{
_foundBox = _box;
return;
}
if (_box.Contents != null) _recurse(_box.Contents);
}
});
_recurse(box.Contents);
return _foundBox;
}
是否有任何方法可以使用 LINQ 来压缩 FindBoxBySize()
?另外:欢迎对我的代码发表评论。我没有做太多递归,所以我可能在实现中遗漏了一些东西。
Consider the following:
public class Box
{
public BoxSize Size { get; set; }
public IEnumerable<Box> Contents { get; set; }
}
Box FindBoxBySize(Box box, BoxSize size)
{
Box _foundBox = null;
Action<IEnumerable<Box>> _recurse = null;
_recurse = new Action<IEnumerable<Box>>(boxes =>
{
foreach (var _box in boxes)
{
if (_box.Size == size)
{
_foundBox = _box;
return;
}
if (_box.Contents != null) _recurse(_box.Contents);
}
});
_recurse(box.Contents);
return _foundBox;
}
Is there any way that FindBoxBySize()
can be compacted using LINQ? Also: comments on my code are welcome. I don't do much recursion, so I might have missed something in my implementation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我还采用扩展方法方法,但使用迭代器方法:
您的 FindBoxBySize 方法现在变为:
您的原始调用代码无需修改即可工作:
I'd also take the extension method approach, but use an iterator method:
Your
FindBoxBySize
method now becomes:Your original calling code works without modification:
扩展方法:
使用方法:
Extension methods:
Usage:
如果你想使用 LINQ,你可以这样做(未经测试):
If you want to use LINQ, you could do something like this (untested):
来使您的递归更清晰(在我看来)
您可以通过编写As for LINQ: LINQ does not come with a good way to handle recursive data Structures 。可以通过向 google 询问“LINQ 递归”来找到几种不同的扩展方法来补救,但我不确定它们是否在这种情况下增加了清晰度。
You could make your recursion a little clearer (in my eyes) by writing
As for LINQ: LINQ does not come with a good way to handle recursive data structures. Several different Extension methods to remedy that can be found by asking google for "LINQ recursion", but I am unsure if they add clarity in this case.