Monday, April 26, 2021

LINQ group --- by Get distinct items of groups

using Console_OrderBy;
using System;
using System.Collections.Generic;
using System.Linq;

class SortTest
{
    public void SortListOfObjectsArrayOrderBy()
    {
        List<Student> students = new List<Student>()
            {
             new Student() { Name = "Ajeet", Age = 27, Gender = "Male", City = "Agra", Scores = 50},
             new Student() { Name = "Mohan", Age = 23, Gender = "Male", City = "Delhi", Scores = 80 },
             new Student() { Name = "Rina", Age = 24, Gender = "Female", City = "Delhi", Scores = 70},
             new Student() { Name = "Mira", Age = 33, Gender = "Female", City = "Agra", Scores = 60 },
             new Student() { Name = "Sita", Age = 28, Gender = "Female", City = "Agra", Scores = 50 },
             new Student() { Name = "Hari", Age = 27, Gender = "Male", City = "Delhi", Scores = 40 },
             new Student() { Name = "Ranjeet", Age = 37, Gender = "Male", City = "Goa", Scores = 50},
             new Student() { Name = "Ravi", Age = 23, Gender = "Male", City = "Delhi", Scores = 30 },
             new Student() { Name = "Roshan", Age = 24, Gender = "Male", City = "Delhi", Scores = 50},
             new Student() { Name = "Bhavna", Age = 33, Gender = "Female", City = "Goa", Scores = 55 },
             new Student() { Name = "Mina", Age = 28, Gender = "Female", City = "Goa", Scores = 45 },
             new Student() { Name = "Ajay", Age = 27, Gender = "Male", City = "Delhi", Scores = 70 },
        };
        
        var queryListObjects = from student in students
                               group student by student.City
                               into groupedCities
                               select groupedCities;

        foreach (var groupc in queryListObjects)
        {
            //each group has a unique key value
            Console.WriteLine(groupc.Key);
            
        }
    }
}
namespace Console_OrderBy
{
    class Program
    {
        static void Main(string[] args)
        {
            SortTest t = new SortTest();
            t.SortListOfObjectsArrayOrderBy();
            Console.ReadKey();
        }
    }
}

\OUTPUT

Agra
Delhi
Goa

No comments:

Post a Comment

Hot Topics