我有 2 个数字列表。
public int[] numbersA = { 0, 2, 4 };
public int[] numbersB = { 1, 3, 5 };
我需要如下输出
预期结果
0 is less than 1
0 is less than 3
0 is less than 5
2 is less than 3
2 is less than 5
4 is less than 5
如何通过LINQ
方法语法实现?
我有 2 个数字列表。
public int[] numbersA = { 0, 2, 4 };
public int[] numbersB = { 1, 3, 5 };
我需要如下输出
0 is less than 1
0 is less than 3
0 is less than 5
2 is less than 3
2 is less than 5
4 is less than 5
如何通过LINQ
方法语法实现?
使用方法语法:
var result = numbersA.SelectMany(c => numbersB, (c, o) => new { c, o })
.Where(d => d.c < d.o)
.Select(v=> v.c + "is less than"+ v.o);
有时,冗长优先于简洁,因为在大多数情况下它更清晰、更容易阅读,尽管打字时间可能会更长。
ForEach
当您使用 Array 而不是 List (List has )时,没有直接的方法可以实现您想要的
但如果你想使用数组,我建议使用Array.ForEach
.
int[] numbersA = new int[] { 0, 2, 4 };
int[] numbersB = new int[] { 1, 3, 5 };
Array.ForEach(numbersA, x =>
{
Array.ForEach(numbersB, y =>
{
if (x < y)
Console.WriteLine(x + " is less than " + y);
});
Console.WriteLine(Environment.NewLine);
});
虽然这个问题无非是无用的业务逻辑,但试一试看起来很有趣。我的解决方案是List.Foreach
而不是Linq
,但它只在一个语句中。
static void Main(string[] args)
{
int[] numsA = { 0, 2, 4 };
int[] numsB = { 1, 3, 5 };
numsA.ToList().ForEach((a) =>
{
numsB.Where(b => b > a).ToList()
.ForEach((x) =>
{
Console.WriteLine("{0}>{1}", a, x);
});
});
}
试试这个:
int[] numbersA = { 0, 2, 4 };
int[] numbersB = { 1, 3, 5 };
var result = numbersA.Select(a => numbersB.Where(b => a < b)
.Select(b => a + " is less than " + b))
.SelectMany(arr => arr)
.ToArray();