Saturday, 9 February 2013

sort the array with even first and then odd C#

sort the array with even first and then odd C#

If array contains Even and odd numbers, first group numbers by even and odd and then sort each group ascending or descending order.  merge each group with other. it can be even numbers first/odd numbers array.

for ex:             int[] intArr = new int[]{10,2,3,4,5,6,7,8,9,1};
 
output: 10      8       6       4       2       9       7       5       3       1

i.e even numbers first in descending order then odd numbers next in descending order.

Here is an example.

void SortEvenandOddNumbersInDescendingOrder()
{
            int[] intArr = new int[]{10,2,3,4,5,6,7,8,9,1};

            var query = from i in intArr
                        group i by (i % 2 == 0) into gevenodd
                    
                        select gevenodd;

           var EvenArray= query.FirstOrDefault().OrderByDescending(d=>d);
           var OddArray = query.LastOrDefault().OrderByDescending(d=>d);

           foreach (var num in EvenArray)
           {
               Console.WriteLine(num);
           }

           foreach (var num in OddArray)
           {
               Console.WriteLine(num);
           }


        var joinarrays  =EvenArray.Union(OddArray);

          Console.WriteLine("final output");

          foreach (var a in joinarrays)
          {
             
              Console.Write(a+"\t");
          }
          intArr=joinarrays.ToArray();

          for (int i = 0; i < intArr.Length; i++)
          {
              Console.Write(intArr[i] + "\t");
          }
        }
     
}

OUTPUT:

10
8
6
4
2
9
7
5
3
1
final output
10      8       6       4       2       9       7       5       3       1
10      8       6       4       2       9       7       5       3       1


Tags:
sort the array with even first and then odd C#,sorting even numbers array,sorting odd numbers array, LINQ union operator, LINQ group by operator,Sorting an array using LINQ,LINQ
OrderByDescending ,LINQ OrderBy.