9 May 2014

How to create groups and sort the groups in c#.net



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace sorted_with_Groups
{
    class Program
    {
        public class Student
        {
            public string First { get; set; }
        }
        public static List<Student> GetStudents()
        {
            List<Student> students = new List<Student>
        {
           new Student {First="adi"},
           new Student {First="balu"},
           new Student {First="reddy"},
           new Student {First="nani"},
           new Student {First="pavan"},
           new Student {First="raghu"},
           new Student {First="ramu"},
           new Student {First="raja"},
           new Student {First="vamsi"},
           new Student {First="cm"},
           new Student {First="pm"},
           new Student {First="hm"},
           new Student {First="sm"}
        };
            return students;
        }
        static void Main(string[] args)
        {
            List<Student> students = GetStudents();
            var sortedGroups =
                from student in students
                orderby student.First
                group student by student.First[0] into newGroup
                orderby newGroup.Key
                select newGroup;


            Console.WriteLine(Environment.NewLine + "sortedGroups:");
            Console.WriteLine("*************************");
            foreach (var studentGroup in sortedGroups)
            {
                Console.WriteLine(studentGroup.Key);
                Console.WriteLine("----------------");
                foreach (var student in studentGroup)
                {
                    Console.WriteLine("{0}", student.First);
                }
                Console.WriteLine("----------------");
            }


            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }



    }
}


OUTPUT


No comments:

Post a Comment