简体   繁体   English

C# 使用 Linq 形式和 lambda 形式:如何在数字数组中找到 x 的所有倍数

[英]C# using Linq form and lambda form : how to find all the multiple of x in an array of numbers

I am trying to create a Linq query and a linq lambda form which would return all the numbers of an array which would be a multiple of x and y.我正在尝试创建一个 Linq 查询和一个 linq lambda 表单,它将返回数组的所有数字,该数组将是 x 和 y 的倍数。 Let's say 4 and 6. The array would look like this: int[] multiple = (3, 6,, 8, 12, 16, 18, 19, 24, 26);假设 4 和 6。数组看起来像这样: int[] multiple = (3, 6,, 8, 12, 16, 18, 19, 24, 26);

The actual answer, the linq query, would return: 6, 12, 16, 18, 24 since they all are multiple of 4 and 6 (x and y).实际答案 linq 查询将返回:6、12、16、18、24,因为它们都是 4 和 6(x 和 y)的倍数。 In short all numbers who don't equal to zero can be removed or vice versa… Something like that.简而言之,所有不等于零的数字都可以被删除,反之亦然……类似的事情。 It would be nice to get both forms.最好同时获得 forms。

I am a newbie so all I have yet:我是新手,所以我还没有:

int[] numbers = { 3, 6, 8, 12, 16, 18, 19, 24, 26 };

int[] multipleOf = number.Where((x) => multiple.All((y) => y % x == 0)).ToList();

I'm not sure if you mean are multiples of "both x and y" or "either x and y", however:我不确定您的意思是“x 和 y”或“x 和 y”的倍数,但是:

int x = 4;
int y = 6;

int[] test = new int[] { 3, 6, 8, 12, 16, 18, 19, 24, 26 };

var test2 = test.Where(i => i % x == 0 || i % y == 0).ToList();

var test3 = (from integer in test
             where integer % x == 0 || integer % y == 0
             select integer).ToList();

Replace "||"替换“||” in the lambda query with "&&" if it should be both rather than either.在 lambda 查询中使用“&&”如果它应该是两者而不是任何一个。 I have included ToList() as you appear to be looking for a list, but you could use ToArray() or consume the enumerable another way.当您似乎正在寻找一个列表时,我已经包含了 ToList(),但您可以使用 ToArray() 或以另一种方式使用可枚举。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM