Saturday, 9 February 2013

sort the array with even first and then odd VB.NET


sort the array with even first and then odd VB.NET

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:             Dim intArr() As Integer =  New Integer() {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.


 Private  Sub SortEvenandOddNumbersInDescendingOrder()
            Dim intArr() As Integer =  New Integer() {10,2,3,4,5,6,7,8,9,1}


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

                        Dim gevenodd As select

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

           Dim num As var
           For Each num In EvenArray
               Console.WriteLine(num)
           Next

           Dim num As var
           For Each num In OddArray
               Console.WriteLine(num)
           Next


        Dim joinarrays As var = EvenArray.Union(OddArray)

          Console.WriteLine("final output")

          Dim a As var
          For Each a In joinarrays

              Console.Write(a+"\t")
          Next
          intArr=joinarrays.ToArray()

          Dim i As Integer
          For  i = 0 To  intArr.Length- 1  Step  i + 1
              Console.Write(intArr(i) + "\t")
          Next
 End Sub
 
 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 VB.NET,sorting even numbers array,sorting odd numbers array, LINQ union operator, LINQ group by operator,Sorting an array using LINQ,LINQ
OrderByDescending ,LINQ OrderBy.