gpt4 book ai didi

c# - LINQ 和递归

转载 作者:太空狗 更新时间:2023-10-29 22:55:22 25 4
gpt4 key购买 nike

考虑以下几点:

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() 吗?另外:欢迎对我的代码发表评论。我没有做太多递归,所以我可能在我的实现中遗漏了一些东西。

最佳答案

我也会采用扩展方法方法,但使用迭代器方法:

public static class BoxEx
{
public static IEnumerable<Box> Flatten(this Box box)
{
yield return box;
if (box.Contents != null)
{
foreach (var b in box.Contents.SelectMany(b2 => Flatten(b2)))
{
yield return b;
}
}
}
}

您的 FindBoxBySize 方法现在变为:

Box FindBoxBySize(Box box, BoxSize size)
{
return (from b in box.Flatten()
where b.Size == size
select b).FirstOrDefault();
}

您的原始调用代码无需修改即可运行:

var small = FindBoxBySize(box, BoxSize.Small);

关于c# - LINQ 和递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4257117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com