我想将以下 Groovy 代码转换为 C#
def find_perfect_numbers(def number) {
(2..number).findAll { x-> (1..(x/2)).findAll{ x % it == 0 }.sum() == x }
}
我从 here 得到的.
这是我所拥有的,但它还没有准备好,也无法编译。我对常规代码的理解不够好。
public List<int> find_perfect_numbers(int number)
{
List<int> lst = new List<int>();
lst = 2.To(number).FindAll(x => (1.To(x/2)).FindAll( x % it == 0).Sum() == x);
return lst;
}
我无法翻译 x % it == 0
部分(因为“it”是一个索引)。
- 我希望 C# 代码看起来尽可能像 groovy 函数。具体来说,行
lst = 2.To( ....
. - 我不想使用不同的解决方案来找到完美的数字(我已经有另一个工作函数)。对我来说,这只是关于语法,而不是关于一个好的“完美数字函数”。
- 可以创建新的(扩展)函数来帮助完成此任务,就像我使用的 To 函数一样:
对于上面的 To 函数,我使用了 StackOverflow 函数: Generating sets of integers in C# 并对其进行了一些更改,以便它返回一个 int 列表而不是一个 int 数组
public static class ListExtensions
{
public static List<int> To(this int start, int end)
{
return Enumerable.Range(start, end - start + 1).ToList();
}
}
有人可以帮助我吗?
===更新===
这就是我现在所拥有的,但它还没有工作,我明白了
DivideByZeroException 在 s.value % s.idx == 0
部分未处理:
lst = 2.To(number).FindAll(x => ((1.To(x / 2)).Select((y, index) => new {value = y, idx = index}).Where( s => s.value % s.idx == 0).Sum(t => t.value) == (decimal)x));
最佳答案
我自己找到的。
lst = 2.To(number)
.FindAll(x => ((1.To(x / 2))
.Select((y, index) => new {value = y, idx = index+1})
.Where( s => x % s.idx == 0)
.Sum(t => t.value) == (decimal)x));
不像 Groovy 那样漂亮,但它确实有效。
关于c#-4.0 - 如何将这个 Groovy 函数转换为 C#?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12018453/