1

I have 2 lists of numbers.

public int[] numbersA = { 0, 2, 4 };
public int[] numbersB = { 1, 3, 5 }; 

I need output like below

Expected Result

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

How is it possible through LINQ method syntax?

Community
  • 1
  • 1
PavanKumar GVVS
  • 859
  • 14
  • 45

4 Answers4

4

With Method syntax:

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);
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
1

At times, verbosity take precedence over brevity as it is clearer and easier to read in most situation, although maybe a bit longer to type.

There is no direct way to achieve what you want as you use Array instead of List (List has ForEach)

But if you want with Arrays I suggest using 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);
});

Demo

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
  • `ForEach` isn't LINQ. It's a `List` method. – Abion47 Feb 24 '17 at 06:44
  • If you're going for the "verbosity is better than brevity for the sake of clarity" argument, you might as well just use a regular `for` or `foreach` instead of `Array.ForEach`. They're both faster, about the same amount of verbose, and are far clearer in their intent. – Abion47 Feb 24 '17 at 07:51
0

Although this question is nothing more than useless business logic, it looks funny to have a try. My solution is List.Foreach rather than Linq, but it is in only one statement.

    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);
            });
        });
    }
Lei Yang
  • 3,970
  • 6
  • 38
  • 59
  • `ForEach` isn't LINQ. It's a method of `List`. – Abion47 Feb 24 '17 at 06:45
  • OP wants a LINQ solution, and `ForEach` isn't LINQ. Therefore, this isn't a solution to his question. – Abion47 Feb 24 '17 at 06:47
  • I think he just want something that looks elegant and one liner enough. Your answer is the best though. S.Akbari is answering with linq but the OP is saying no, don't you think him funny? – Lei Yang Feb 24 '17 at 06:48
0

Give this a try:

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();
Abion47
  • 22,211
  • 4
  • 65
  • 88