How to split array of numbers into two groups by criteria in C#

1 Answer

0 votes
using System;
using System.Linq;

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

        var result = from n in arr
                        group n by (n % 2 == 0) into groups
                        select groups;


        foreach (IGrouping<bool, int> group in result) {
            if (group.Key == true)
                Console.WriteLine("Divide by 2");
            else
                Console.WriteLine("Not Divide by 2");

            foreach (int number in group)
                Console.WriteLine(number);
        }
    }
}



/*
run:

Not Divide by 2
1
3
5
7
9
11
13
Divide by 2
2
4
6
8
10
12

*/

 



answered Dec 30, 2022 by avibootz

Related questions

2 answers 269 views
1 answer 266 views
1 answer 205 views
1 answer 178 views
1 answer 204 views
...