谁能告诉我如何以最佳方式将以下代码转换为 LINQ:
static int MyMethod(MyClass my, bool b)
{
int cnt = 0;
foreach(SomeClass cls in my.SomeMethod()
{
cnt = cnt + cls.length;
}
if(b == true)
{
foreach(MyClass aa in my.SomeOtherMethod())
{
cnt = cnt + MyMethod(aa, true); // recursive
}
}
return cnt;
}
请注意,我知道上面的代码工作正常,但我需要在 LINQ 中编写它并进行比较。
最佳答案
正如 Darin 所说,如果不明确这样做,您就无法轻松递归 - 但您仍然可以使用 LINQ 简化此代码:
static int MyMethod(MyClass my, bool b)
{
int cnt = my.SomeMethod().Sum(cls => cls.length);
if (b)
{
cnt += my.SomeOtherMethod().Sum(aa => MyMethod(aa, true));
}
return cnt;
}
关于c# - 如何将此递归代码转换为 Linq,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3123014/