How to use GroupBy() transforms an int array into groups in C#

2 Answers

0 votes
using System;
using System.Linq;

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

            var allGroups = arr.GroupBy(a => IsOdd(a));

            foreach (var group in allGroups)
            {
                Console.WriteLine("IsOdd = {0}", group.Key);

                foreach (var n in group)
                    Console.Write("{0} ", n);

                Console.WriteLine();
            }
        }
        static bool IsOdd(int n)
        {
            return n % 2 != 0;
        }
    }
}


/*
run:
     
IsOdd = True
1 3 5 7 9 11 13
IsOdd = False
2 4 6 8 10 12

*/

 



answered Feb 22, 2017 by avibootz
0 votes
using System;
using System.Linq;

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

            var allGroups = from element in arr
                            orderby element
                            group element by IsOdd(element);

            foreach (var group in allGroups)
            {
                Console.WriteLine("IsOdd = {0}", group.Key);

                foreach (var n in group)
                    Console.Write("{0} ", n);

                Console.WriteLine();
            }
        }
        static bool IsOdd(int n)
        {
            return n % 2 != 0;
        }
    }
}


/*
run:
     
IsOdd = True
1 3 5 7 9 11 13
IsOdd = False
2 4 6 8 10 12

*/

 



answered Feb 22, 2017 by avibootz

Related questions

1 answer 163 views
2 answers 235 views
1 answer 78 views
4 answers 311 views
1 answer 182 views
...