Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,924 questions

51,857 answers

573 users

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 133 views
2 answers 214 views
1 answer 61 views
4 answers 278 views
1 answer 166 views
...