我想编写一个程序,它可以从给定的整数数组中打印那些可以被3和9整除的数字。我想要使用内置扩展方法和lambda表达式。 我做了什么:Lambda表达式数字可被9和3整除c#
static void Main(string[] args)
{
List<int> l = new List<int>() {18,3,27,42};
List<int> divBy3 = l.FindAll(x => (x % 9) == 0);
List<int> divBy9 = l.FindAll(x => (x % 3) == 0);
if (divBy9 == divBy3)
{
foreach (var num in divBy9)
{
Console.WriteLine("The numbers divisible by 9 and 3 are: {0}",num);
}
}
else
{
Console.WriteLine("There are no numbers divisible by 9 and 3.");
}
}
和输出应该是{} 27,18。 我的输出总是else分支,但我不明白为什么。我试图把原始的整数数组中只有值{18,27},它应该验证相等性。在foreach中,我只是检查在divBy9列表中,因为我认为如果2个列表是相同的,只能在一个列表中检查,但我认为不好。 有什么问题?谢谢。
'X% 3 == 0'是没有意义的,因为它被'x%9 == 0'检查所隐含。 – MarcinJuraszek
@MarcinJuraszek是的,我想你是对的,这是有点尴尬,因为我其实有一个数学学位。 –
@BradfordDillon根据OP提供的样本输入和输出,他希望数字可以同时被9 **和** 3共同识别 - 输入序列中有'3',但不是期望的输出。 – MarcinJuraszek