How to split an array of int numbers into two groups by condition with C#

1 Answer

0 votes
using System;
using System.Linq;

class Program
{
    static void Main() {
        int[] arr = { 2, 5, 4, 6, 8, 7, 9, 1, 3 };

        var all_groups = from n in arr
                        group n by (n % 2 == 0) into groups
                        select groups;
    
        foreach (IGrouping<bool, int> group in all_groups) {
            if (group.Key == true)
                Console.WriteLine("Divisible by 2");
            else
                Console.WriteLine("Not Divisible by 2");
    
            foreach (int number in group)
                Console.WriteLine(number);
        }
    }
}



/*
run:

Divisible by 2
2
4
6
8
Not Divisible by 2
5
7
9
1
3

*/

 



answered Mar 10, 2021 by avibootz
edited Mar 10, 2021 by avibootz
...