比较 LINQ 方法语法中的 2 个数字列表

Compare 2 Lists of numbers in LINQ Method Syntax

我有 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.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();