Monday, 9 July 2018

Group By and ToLookup in Linq C#





using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;



namespace ConsoleApplication1

{

    class student

    {

        public int studentID { get; set; }

        public string studentName { get; set; }

        public int Age { get; set; }

    }

    class Program

    {

        static void Main(string[] args)

        {

            List<student> li = new List<student>()

          {



             new student() { studentID = 5, studentName = "Ron" , Age = 21 },

            new student() { studentID = 6, studentName = "Chris",  Age = 18 },

             new student() { studentID = 7, studentName = "Rob",Age = 19  },

            new student() { studentID = 8, studentName = "Rob",Age = 21  },

            new student() { studentID = 1, studentName = "John", Age = 18 },

            new student() { studentID = 2, studentName = "Steve",  Age = 21 },

            new student() { studentID = 3, studentName = "Bill",  Age = 25 },

            new student() { studentID = 4, studentName = "Ram" , Age = 19 },

            new student() { studentID = 9, studentName = "Bill",Age = 19  },



        };



           // var agegroup = li.GroupBy(x => x.Age).ToList();

            var agegroup = li.ToLookup(x => x.Age).ToList();

            foreach (var group in agegroup)

            {

                Console.ForegroundColor = System.ConsoleColor.Green;



                Console.WriteLine("====AGE:"+group.Key+"====");

                Console.ForegroundColor = System.ConsoleColor.Red;



                foreach (var item  in group)

                {

                    Console.WriteLine(item.studentName);

                }

               

            }





     





        }

    }

}


No comments:

Post a Comment

Pass Dynamically Added Html Table Records List To Controller In Asp.net MVC

Controller Code: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using ...