Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

Wednesday, May 5, 2021

LINQ Simple Examples with clauses

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

namespace LinqExercises
{
    class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public char Gender { get; set; }
    }
    class Test
    {
        public void Exercise1() //integer array
        {
            int[] data = { 8, 4, 1, 2, 6, 5, 7, 9, 3 };
            IEnumerable<int> queryvar = from rangevar in data
                                        where rangevar % 2 == 0 && rangevar > 5
                                        select rangevar;
            Console.WriteLine("Query Array:-->");
            foreach (var item in queryvar)
            {
                Console.WriteLine(item);
            }
        }
        public void Exercise2() //string array
        {
            string[] names = { "Aryaman", "Bhaavik", "Bhavin", "Chitaksh", "Daksh", "Darshit", "Devansh", "Dhanuk", "Dhairya", "Divij", "Divyansh", "Ehsaan", "Eeshan", "Faiyaz", "Farhan" };
            IEnumerable<string> query1 = from n in names
                                        where n.Contains("an")
                                        select n;
            Console.WriteLine("query1:-->");
            foreach (var q in query1)
            {
                Console.WriteLine(q);
            }
            Console.WriteLine("query2:-->");
            IEnumerable<string> query2 = from n in names
                                         where n.StartsWith("Dh")
                                         select n;
            foreach (var q in query2)
            {
                Console.WriteLine(q);
            }
            Console.WriteLine("query3:-->");
            IEnumerable<string> query3 = from n in names
                                         where n.EndsWith("h")
                                         select n;
            foreach (var q in query3)
            {
                Console.WriteLine(q);
            }
        }
        public void Exercise3()
        {
            Student s1 = new Student() { Id = 1, Name = "Ajay", Age = 29, Gender = 'M' };
            Student s2 = new Student() { Id = 2, Name = "Rina", Age = 21, Gender = 'F' };
            Student s3 = new Student() { Id = 3, Name = "Ajeet", Age = 25, Gender = 'M' };
            Student s4 = new Student() { Id = 4, Name = "Alok", Age = 21, Gender = 'M' };
            Student s5 = new Student() { Id = 5, Name = "Pankaj", Age = 27, Gender = 'M' };
            Student s6 = new Student() { Id = 6, Name = "Kamni", Age = 21, Gender = 'F' };
            Student s7 = new Student() { Id = 7, Name = "Priya", Age = 23, Gender = 'F' };
            List<Student> students = new List<Student>();
            students.Add(s1);
            students.Add(s2);
            students.Add(s3);
            students.Add(s4);
            students.Add(s5);
            students.Add(s6);
            students.Add(s7);

            var querystds = from std in students
                            where std.Age > 25
                            orderby std.Name
                            select std;
            Console.WriteLine("Query List of students:-->");
            foreach (var std in querystds)
            {
                Console.Write("{0} {1} {2}", std.Id, std.Name, std.Age);
                Console.WriteLine();
            }

            var groupedGender = from s in students
                                group s by s.Gender into GrpStudent
                                select new
                                {
                                    Sex = GrpStudent.Key,
                                    AverageAge = Math.Round(GrpStudent.Average(g => g.Age), 2)
                                } ;
            foreach (var gg in groupedGender)
            {
                Console.WriteLine(gg);
            }
            Console.WriteLine("GROUPED DATA:");
            var grps = from s in students
                       group s by s.Gender;
            foreach (var grp in grps)
            {
                foreach (var gr in grp)
                {
                    Console.WriteLine("{0} {1} {2} {3}",gr.Id,gr.Name,gr.Age,gr.Gender);
                }

            }
            Console.WriteLine("SORTED GROUPED DATA:");
            var sortgrps = from s in students
                       orderby s.Gender
                       group s by s.Gender;
            foreach (var grp in sortgrps)
            {
                foreach (var gr in grp)
                {
                    Console.WriteLine("{0} {1} {2} {3}", gr.Id, gr.Name, gr.Age, gr.Gender);
                }

            }
            Console.WriteLine("STATISTICAL FIGURES");
            var statgrps = from s in students
                           orderby s.Gender
                           group s by s.Gender;
            foreach (var gr in statgrps)
            {
                Console.WriteLine("Sum of {0}: {1}", gr.Key, gr.Sum(s => s.Age));
                Console.WriteLine("Max of {0}: {1}", gr.Key, gr.Max(s => s.Age));
                Console.WriteLine("Min of {0}: {1}", gr.Key, gr.Min(s => s.Age));
                Console.WriteLine("Average of {0}: {1}", gr.Key, Math.Round(gr.Average(s => s.Age),2));
                Console.WriteLine("Count of {0}: {1}",gr.Key ,gr.Count());
                Console.WriteLine("Count of {0} whose age is 21: {1}",gr.Key ,gr.Count(s=>s.Age==21));
                Console.WriteLine();
            }
        }
        public void Exercise4()
        {
            Console.WriteLine("Illustration of deferred execution");
            int[] data = { 9, 2, 1, 8, 4, 6, 0 };
            List<int> even = new List<int>();

            for (int i = 0; i < data.Length; i++)
            {
                if (data[i] % 2 == 0)
                {
                    even.Add(data[i]);
                }
            }
            data[2] = 6;
            //display even
            foreach (var e in even)
            {
                Console.Write(e.ToString() +" ");
            }

            int[] data2 = { 9, 2, 1, 8, 4, 6, 0 };
            IEnumerable<int> queryvar = from r in data2
                                        where r % 2 == 0
                                        select r;
            data2[2] = 6;
            //display query result
            //execute query using for each loop
            // query deffered until foreach loop used
            Console.WriteLine();
            foreach (var e in queryvar)
            {
                Console.Write(e.ToString() + " ");

            }

        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Test t = new Test();
            t.Exercise1();
            t.Exercise2();
            t.Exercise3();
            t.Exercise4();
            Console.ReadKey();
        }
    }
}

OUTPUT
Query Array:-->
8
6
query1:-->
Aryaman
Devansh
Dhanuk
Divyansh
Ehsaan
Eeshan
Farhan
query2:-->
Dhanuk
Dhairya
query3:-->
Chitaksh
Daksh
Devansh
Divyansh
Query List of students:-->
1 Ajay 29
5 Pankaj 27
{ Sex = M, AverageAge = 25.5 }
{ Sex = F, AverageAge = 21.67 }
GROUPED DATA:
1 Ajay 29 M
3 Ajeet 25 M
4 Alok 21 M
5 Pankaj 27 M
2 Rina 21 F
6 Kamni 21 F
7 Priya 23 F
SORTED GROUPED DATA:
2 Rina 21 F
6 Kamni 21 F
7 Priya 23 F
1 Ajay 29 M
3 Ajeet 25 M
4 Alok 21 M
5 Pankaj 27 M
STATISTICAL FIGURES
Sum of F: 65
Max of F: 23
Min of F: 21
Average of F: 21.67
Count of F: 3
Count of F whose age is 21: 2

Sum of M: 102
Max of M: 29
Min of M: 21
Average of M: 25.5
Count of M: 4
Count of M whose age is 21: 1

Illustration of deferred execution
2 8 4 6 0
2 6 8 4 6 0

Monday, April 26, 2021

LINQ Method Syntax based simple queries

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

namespace Console__LINQ_QueriesOnListCollection
{
    class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Gender { get; set; }
        public string City { get; set; }
        public int Scores { get; set; }

        public List<Student> GetStudents()
        {
            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 = 33, 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 },
            };
            return _students;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Student s = new Student();
            List<Student>  students = s.GetStudents();
            var query1 = students.Where(s => s.City == "Delhi" && s.Gender == "Male");
            Console.WriteLine("\nResult of query1\n");
            foreach (var item in query1)
            {
                Console.WriteLine(item.Name + " " + item.Age);

            }
            var query2 = students.Where(s => s.City == "Delhi" && s.Gender == "Male").FirstOrDefault();
            Console.WriteLine("\nResult of query2\n");
            Console.WriteLine(query2.Name+ " "+ query2.Age);

            //find all names that starts with letter R
            Console.WriteLine("\nResult of query3\n");
            var query3 = students.Where(s => s.Name[0] == 'R').ToList();
            foreach (var item in query3)
            {
                Console.WriteLine(item.Name);
            }
            //find all names that starts with letter R, SQL syntax
            Console.WriteLine("\nResult of query4\n");
            var query4 = from student in students
                         where student.Name.StartsWith('R')
                         select student;
            foreach (var item in query4)
            {
                Console.WriteLine(item.Name);
            }

            //find average age of students
            Console.WriteLine(students.Average(s => s.Age).ToString());
            //find sum of all scores
            Console.WriteLine(students.Sum(s=>s.Scores).ToString());
            //find average age of male students, first filter 
            Console.WriteLine(students.Where(s =>s.Gender == "Male").Average(s=>s.Age));
            //display records of students who live in Delhi or Agra and are female
            var query6 = students.Where(s => (s.City == "Delhi" || s.City == "Agra") && s.Gender=="Female");
            Console.WriteLine("\nResult of query6\n");
            foreach (var std in query6)
            {
                Console.WriteLine("{0}, {1}, {2}, {3} ", std.Name, std.Age, std.Gender, std.City);
            }
            var query7 = students.Where(s => (s.City == "Delhi" || s.City == "Agra") && s.Gender == "Female").Average(s => s.Age);
            Console.WriteLine("\nResult of query7 : Where() Average()\n");
            Console.WriteLine("Average Age of female students living in Agra or Delhi: " + query7);
            //find total number of distinct cities
            Console.WriteLine("Distinct cities #:"+students.GroupBy(s => s.City).Count());
            //sort the students cities in ascending order
            Console.WriteLine("\nResult of query8: OrderBy\n");
            var query8 = students.OrderBy(s => s.City);
            foreach (var std in query8)
            {
                Console.WriteLine("{0} {1} ", std.City, std.Name);
            }
            //sort city and then name
            Console.WriteLine("\nResult of query9: OrderBy ThenBy\n");
            var query9 = students.OrderBy(s => s.City).ThenBy(s => s.Name);
            foreach (var q9 in query9)
            {
                Console.WriteLine("{0} {1} ",q9.City, q9.Name);

            }

            var queryCity = students.GroupBy(s => s.City);
/* The datatype of queryCity is IEnumerable<IGrouping<string, Student>> Place the cursor at queryCity to get this fact. Here, string is all about the data type of the city column used in grouping. Remember that in LINQ datatype is strictly type */
            Console.WriteLine("\nGROUP STUDENTS BY CITY");
            foreach (var gcity in queryCity)
            {
                Console.WriteLine(gcity.Key +" Group:->");
                foreach (var stt in gcity)
                {
                    Console.WriteLine("{0} {1} {2} {3} {4}",stt.Name, stt.Age, stt.Gender,stt.City,stt.Scores);
                }
            }
            Console.WriteLine("\nGROUP STUDENTS BY CITY AND GENDER");
            // Note the + sign used to concatenate multilevel grouping based on Gender and City
            var qGenderCity = students.GroupBy(s => s.Gender+ s.City);
            foreach (var gcityGender in qGenderCity)
            {
                Console.WriteLine(gcityGender.Key);
                foreach (var stt in gcityGender)
                {
                    Console.WriteLine("{0} {1} {2} {3} {4}", stt.Name, stt.Age, stt.Gender, stt.City, stt.Scores);
                }
                Console.WriteLine();
            }
            Console.WriteLine("NESTED QUERY:");
            var queryNested = from student in students
                              group student by student.City
                              into newStd
                              from grps in newStd
                              group grps by grps.Gender;
            foreach (var gcg in queryNested)
            {
                Console.WriteLine(gcg.Key);
                foreach (var g in gcg)
                {
                    Console.WriteLine("{0} {1} {2} {3}", g.City, g.Gender, g.Name,g.Age);
                }
            }
            Console.WriteLine("MAXIMUM AVERAGE SCORE OF EACH GROUP/CITY");
            var qGrpAvg = from sdn in students
                          group sdn by sdn.City into gsCity
                          select new
                          {
                              HighestAvg = Math.Round(((from scoregcity in gsCity
                                                        select scoregcity.Scores).Average()),2)
                          };
            foreach (var item in qGrpAvg)
            {     
                Console.WriteLine(item);
            }
            var qmax = (from q in qGrpAvg
                       select q.HighestAvg).Max();
            Console.WriteLine("Maximum average score: {0}",qmax);
            Console.ReadKey();
        }
    }
}


OUTPUT

Result of query1

Mohan 23
Hari 27
Ravi 23
Roshan 24
Ajay 27

Result of query2

Mohan 23

Result of query3

Rina
Ranjeet
Ravi
Roshan

Result of query4

Rina
Ranjeet
Ravi
Roshan
28.25
650
26.857142857142858

Result of query6

Rina, 24, Female, Delhi
Mira, 33, Female, Agra
Sita, 33, Female, Agra

Result of query7 : Where() Average()

Average Age of female students living in Agra or Delhi: 30
Distinct cities #:3

Result of query8: OrderBy

Agra Ajeet
Agra Mira
Agra Sita
Delhi Mohan
Delhi Rina
Delhi Hari
Delhi Ravi
Delhi Roshan
Delhi Ajay
Goa Ranjeet
Goa Bhavna
Goa Mina

Result of query9: OrderBy ThenBy

Agra Ajeet
Agra Mira
Agra Sita
Delhi Ajay
Delhi Hari
Delhi Mohan
Delhi Ravi
Delhi Rina
Delhi Roshan
Goa Bhavna
Goa Mina
Goa Ranjeet

GROUP STUDENTS BY CITY
Agra Group:->
Ajeet 27 Male Agra 50
Mira 33 Female Agra 60
Sita 33 Female Agra 50
Delhi Group:->
Mohan 23 Male Delhi 80
Rina 24 Female Delhi 70
Hari 27 Male Delhi 40
Ravi 23 Male Delhi 30
Roshan 24 Male Delhi 50
Ajay 27 Male Delhi 70
Goa Group:->
Ranjeet 37 Male Goa 50
Bhavna 33 Female Goa 55
Mina 28 Female Goa 45

GROUP STUDENTS BY CITY AND GENDER
MaleAgra
Ajeet 27 Male Agra 50

MaleDelhi
Mohan 23 Male Delhi 80
Hari 27 Male Delhi 40
Ravi 23 Male Delhi 30
Roshan 24 Male Delhi 50
Ajay 27 Male Delhi 70

FemaleDelhi
Rina 24 Female Delhi 70

FemaleAgra
Mira 33 Female Agra 60
Sita 33 Female Agra 50

MaleGoa
Ranjeet 37 Male Goa 50

FemaleGoa
Bhavna 33 Female Goa 55
Mina 28 Female Goa 45

NESTED QUERY:
Male
Agra Male Ajeet 27
Delhi Male Mohan 23
Delhi Male Hari 27
Delhi Male Ravi 23
Delhi Male Roshan 24
Delhi Male Ajay 27
Goa Male Ranjeet 37
Female
Agra Female Mira 33
Agra Female Sita 33
Delhi Female Rina 24
Goa Female Bhavna 33
Goa Female Mina 28
MAXIMUM AVERAGE SCORE OF EACH GROUP/CITY
{ HighestAvg = 53.33 }
{ HighestAvg = 56.67 }
{ HighestAvg = 50 }
Maximum average score: 56.67

LINQ to Objects

using System;
using System.Linq;
/*
 * Query using C# and doing it again using LINQ
 * Deferrred LINQ query Execution
 */
namespace Console_LINQ_DeferredQueryExecution
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = { 1, 2, 3, 4, 6, 7, 9, 5, 8 };
            //find all even numbers using C#, before LINQ was invented
            Console.WriteLine("\n===========C# to Objects==========\n");
            for (int i = 0; i < numbers.Length; i++)
            {
                if (numbers[i] % 2 == 0)
                {
                    Console.WriteLine(numbers[i]);
                }
            }
            
            Console.WriteLine("\n===========LINQ to Objects==========\n");
            int[] numbers2 = { 1, 2, 3, 4, 6, 7, 9, 5, 8 };
            //LINQ SQL based syntax
            var query = from number in numbers2
                        where number % 2 == 0
                        select number;
            //Method syntax
            //var query = numbers.Where(number => number % 2 == 0);
            foreach (var item in query)
            {
                Console.WriteLine(item);
            }
            
            Console.ReadKey();
        }
    }
}
OUTPUT
===========C# to Objects==========

2
4
6
8

===========LINQ to Objects==========

2
4
6
8

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

LINQ Sort Array & List using OrderBy, GroupBy keywords

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

class SortTest
{
    public void SortIntArrayOrderBy()
    {
        int[] numbers = { 7, 5, 9, 8, 1, 6, 2, 4, 3, 9 };
        //SQL syntax
        /*
        IOrderedEnumerable<int> queryNums = from number in numbers
                                    orderby number ascending
                                    select number;
        */
        //method syntax
        IOrderedEnumerable<int> queryNums = numbers.OrderBy(number => number);
        //execute query
        foreach (var item in queryNums)
        {
            Console.WriteLine(item);

        }
    }
    public void SortStrArrayOrderBy()
    {
        string[] cities = { "Goa", "Nagpur", "London", "Paris", "Delhi", "Chennai" };
        //SQL syntax
        /*
        IOrderedEnumerable<string> queryStrs = from city in cities
                                            orderby city
                                            select city;
        */
        //method syntax
        var queryStrs = cities.OrderBy(city => city);
        foreach (var item in queryStrs)
        {
            Console.WriteLine(item);

        }
    }
    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
        //                       orderby student.City
        //                       select student.City;
        //var queryListObjects = from student in students
        //                       group student by student.City
        //                       into groupedCities
        //                       orderby groupedCities.Key
        //                       select groupedCities;
        //Console.WriteLine(System.Environment.NewLine);
        var queryListObjects = students.GroupBy(student => student.City);
        Console.WriteLine("Groups #: "+queryListObjects.Count());
        foreach (var groupc in queryListObjects)
        {
            //each group has a unique key value
            Console.WriteLine(groupc + " ---->> " + groupc.Key + " " + groupc.Count());
            foreach (var s in groupc)
            {
                //console.writeline(s); // student class
                Console.WriteLine(" *** " + s.City);
            }

        }
    }
}
namespace Console_OrderBy
{
    class Program
    {
        static void Main(string[] args)
        {
            SortTest t = new SortTest();
            t.SortIntArrayOrderBy();
            t.SortStrArrayOrderBy();
            t.SortListOfObjectsArrayOrderBy();
            Console.ReadKey();
        }
    }
}

OUTPUT

1
2
3
4
5
6
7
8
9
9
Chennai
Delhi
Goa
London
Nagpur
Paris
Groups #: 3
System.Linq.Grouping`2[System.String,Console_OrderBy.Student] ---->> Agra 3
 *** Agra
 *** Agra
 *** Agra
System.Linq.Grouping`2[System.String,Console_OrderBy.Student] ---->> Delhi 6
 *** Delhi
 *** Delhi
 *** Delhi
 *** Delhi
 *** Delhi
 *** Delhi
System.Linq.Grouping`2[System.String,Console_OrderBy.Student] ---->> Goa 3
 *** Goa
 *** Goa
 *** Goa

Saturday, April 24, 2021

LINQ let clause Example

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

namespace Console_LINQ_let_clause
{
    class LinqClauses
    {
        public void LinqExample01()
        {
            Console.WriteLine("\nLinqExample01");
            List<string> fullnames = new List<string>()
            {
                "Ajeet Kumar", "Rajeev Gupta", "Mohit Sharma", "Vinay Dubey",
                "Amit Gupta", "Mira Gupta", "Arvind Sharma", "Sagar Gupta"
            };
            //find all first names using LINQ
            var queryvar = from fullname in fullnames
                          select fullname.Split(' ')[0];
            //execute queryvar
            foreach (var item in queryvar)
            {
                Console.WriteLine(item);
            }

        }

        public void LinqExample02()
        {
            Console.WriteLine("\nLinqExample02");
            List<string> fullnames = new List<string>()
            {
                "Arjun Kumar", "Krishna Gupta", "Maya Sharma", "Bhim Dubey",
                "Nakul Gupta", "Radha Gupta", "Arvind Sharma", "Sagar Gupta"
            };
            //find all first names using LINQ
            /*
             * let clause is used to store the result of an expression 
             * let variable is new range variable
             * fullname is range variable which is replaced by firstname
             */
            var firstnames = from fullname in fullnames
                           let firstname = fullname.Split(' ')[0]
                           select firstname;
            //execute firstnames
            foreach (var first in firstnames)
            {
                Console.WriteLine(first);
            }

        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            LinqClauses c = new LinqClauses();
            c.LinqExample01();
            c.LinqExample02();
            Console.ReadKey();
        }
    }
}

OUTPUT


LinqExample01
Ajeet
Rajeev
Mohit
Vinay
Amit
Mira
Arvind
Sagar

LinqExample02
Arjun
Krishna
Maya
Bhim
Nakul
Radha
Arvind
Sagar

LINQ SQL clauses Examples- from, where, group, into, and select clauses

using System;
using System.Collections.Generic;
using System.Linq;
/*
 * Data Source
 * Concept of Sequence
 * Query vs Query result
 * Query Expression
 * Query vs Query variable
 * Query variable as Enumerable type
 * IEnumerable type
 * IEnumerable of generic type
 * Difference between Query and 
 * Range variable vs Query variable
 * Method call in Query
 * Single Query with Multiple data sources
 * Query without data transformation of data source returning filtered data
 * Query without data transformation of data source returing count, min, max, average etc. single figure
 * Query with data transformation of data source
 * required clauses from , select or group
 * LINQ query expression must begin with from clause.
 * LINQ query expression must end with either a group clause or a select clause.
 */

namespace Console_LINQ_QueryExpression
{
    class Student
    {
        //auto-implemented properties
        public string Name { get; set; }
        public string Gender { get; set; }
        public string City { get; set; }
        public int Age { get; set; }
        public int[] Scores { get; set; }
    }
    class Test
    {
        public void Linq_Example_01()
        {
            Console.WriteLine("Linq_Example_01: Display data source items");
            /*LINQ with mandatory from and select clauses
             *Data source is initialized directly in LINQ
             */
            var queryvar = from rangevar 
                           in new int[] { 1, 2, 3, 4, 7, 6, 5, 9 }
                           select rangevar;
            foreach (var number in queryvar)
            {
                Console.Write(number + " ");
            }
        }
        public void Linq_Example_02()
        {
            Console.WriteLine("\nLinq_Example_02: where clause to filter source data");
            /*LINQ with where clause */
            var queryvar = from rangevar 
                           in new int[] { 1, 2, 3, 4, 7, 6, 5, 9 }
                           where rangevar > 4
                           select rangevar;
            foreach (var number in queryvar)
            {
                Console.Write(number + " ");
            }
        }
        public void Linq_Example_03()
        {
            Console.WriteLine("\nLinq_Example_03 : orderby clause to sort data source");
            /*LINQ with orderby clause */
            var queryvar = from rangevar
                           in new int[] { 1, 2, 3, 4, 7, 6, 5, 9 }
                           orderby rangevar
                           select rangevar;
            foreach (var number in queryvar)
            {
                Console.Write(number + " ");
            }
        }

        public void Linq_Example_04()
        {
            Console.WriteLine("\nLinq_Example_04 : where and orderby clauses to sort filtered data source");
            /*LINQ with where clause */
            var queryvar = from rangevar
                           in new int[] { 1, 2, 3, 4, 7, 6, 5, 9 }
                           where rangevar > 4
                           orderby rangevar
                           select rangevar;
            foreach (var number in queryvar)
            {
                Console.Write(number + " ");
            }
        }

        public void Linq_Example_05()
        {
            Console.WriteLine("\nLinq_Example_05 : Sorted words and Explicit datatype of range variable and query variable" );
            string[] words = "Think for yourself and let others enjoy the privilege of doing so too.".Split(' ');
            IEnumerable<string> varquery = from string word in words
                       orderby word
                       select word;
            foreach (string wd in varquery)
            {
                Console.Write(wd + " ");
            }
        }

        public void Linq_Example_06()
        {
            Console.WriteLine("\nLinq_Example_06 : group clause with by contextual clause");
            List<Student> students = new List<Student>()
            {
             new Student() { Name = "Ajeet", Age = 27, Gender = "Male", City = "Agra", Scores = new int[]{ 75, 30, 40, 55, 60 } },
             new Student() { Name = "Mohan", Age = 23, Gender = "Male", City = "Delhi", Scores = new int[]{ 55, 60, 20, 30, 40} },
             new Student() { Name = "Rina", Age = 24, Gender = "Female", City = "Delhi", Scores = new int[]{ 40, 30, 45, 55, 77 } },
             new Student() { Name = "Mira", Age = 33, Gender = "Female", City = "Agra", Scores = new int[]{ 80, 43, 40, 55, 69 } },
             new Student() { Name = "Sita", Age = 28, Gender = "Female", City = "Agra", Scores = new int[]{ 70, 20, 40, 59, 32 } },
             new Student() { Name = "Hari", Age = 27, Gender = "Male", City = "Delhi", Scores = new int[]{ 54, 70, 20, 40, 90} },
        };
            var groupedstudents = from student in students
                           group student by student.Gender;
            foreach (var item in groupedstudents)
            {
                //list all the items of Gender key
                Console.WriteLine(item.Key);
            }
            Console.WriteLine("Example of into clause for subquery:--");
            var malestudents = from student in students
                               group student by student.Gender
                               into males
                               where males.Key=="Male"
                               select males;
            foreach (var malestudent in malestudents)
            {
                //Console.WriteLine(malestudent.Key);
                foreach (var m in malestudent)
                {
                
                    Console.WriteLine(m.Name+ ", " + m.City + ", " +
                        m.Gender + ", "+ m.Age);
                }
            }
            Console.WriteLine("List Females:-----");
            var femalestudents = from student in students
                                 where student.Gender == "Female"
                                 group student by student.City
                                 into females
                                 select females;

            foreach (var femalestudent in femalestudents)
            {
                foreach (var f in femalestudent)
                {
                    Console.WriteLine(f.Name + ", " + f.City + ", " 
                        + f.Gender + ", " + f.Age);
                }
            }


        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Test t = new Test();
            t.Linq_Example_01();
            t.Linq_Example_02();
            t.Linq_Example_03();
            t.Linq_Example_04();
            t.Linq_Example_05();
            t.Linq_Example_06();

        }
    }
}

OUTPUT

Linq_Example_01: Display data source items
1 2 3 4 7 6 5 9
Linq_Example_02: where clause to filter source data
7 6 5 9
Linq_Example_03 : orderby clause to sort data source
1 2 3 4 5 6 7 9
Linq_Example_04 : where and orderby clauses to sort filtered data source
5 6 7 9
Linq_Example_05 : Sorted words and Explicit datatype of range variable and query variable
and doing enjoy for let of others privilege so the Think too. yourself
Linq_Example_06 : group clause with by contextual clause
Male
Female
Example of into clause for subquery:--
Ajeet, Agra, Male, 27
Mohan, Delhi, Male, 23
Hari, Delhi, Male, 27
List Females:-----
Rina, Delhi, Female, 24
Mira, Agra, Female, 33
Sita, Agra, Female, 28

Tuesday, April 20, 2021

LINQ let Clause Examples

LINQ has three parts:
  1. Data source 
  2. Query of data source
  3. Execution of Query
A query expression must begin with a from clause. Additionally, a query expression can contain sub-queries, which also begin with a from clause.

The from clause specifies the following:
  • The data source on which the query or sub-query will be run.
  • A local range variable that represents each element in the source sequence.
  • Both the range variable and the data source are strongly typed.

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/from-clause
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/let-clause


EXAMPLE 1


using System.Linq;
using System.Web.Mvc;

namespace Mvc_LINQ_let_clause.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public string Index()
        {
            //data source
            string[] Quotes =
            {
            "Everything you can imagine is real.",
            "Whatever you do, do it well.",
            "What we think, we become."
            };

            //LINQ query
            var Query =
            from sentence in Quotes
            let words = sentence.Split(' ')
            from word in words
            select word;

            
            //Excecute Query
            foreach (var letter in Query)
            {
                Response.Write(letter);
                Response.Write("
"); } return ""; } } }

OUTPUT:
Everything
you
can
imagine
is
real.
Whatever
you
do,
do
it
well.
What
we
think,
we
become.

EXAMPLE 2


using System.Linq;
using System.Web.Mvc;

namespace Mvc_LINQ_let_clause.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public string Index()
        {
            //data source
            string[] Quotes =
            {
            "Everything you can imagine is real.",
            "Whatever you do, do it well.",
            "What we think, we become."
            };

            //LINQ query
            var Query =
            from quote in Quotes
            where quote.Contains("What")
            select quote.ToUpper();

            
            //Excecute Query
            foreach (var WhatQuote in Query)
            {
                Response.Write(WhatQuote);
                Response.Write("
"); } return ""; } } }

OUTPUT:

WHATEVER YOU DO, DO IT WELL.
WHAT WE THINK, WE BECOME.

EXAMPLE 3


using System.Linq;
using System.Web.Mvc;

namespace Mvc_LINQ_let_clause.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public string Index()
        {
            //data source
            string[] Quotes =
            {
            "Everything you can imagine is real.",
            "Whatever you do, do it well.",
            "What we think, we become."
            };

            //LINQ query
            var Query =
            from quote in Quotes
            where quote.Contains("What")
            //Note Split function has charater parameter in single quotation mark
            let clauses = quote.Split(',')
            from clause in clauses
            select clause.ToUpper();

            
            //Excecute Query
            foreach (var cl in Query)
            {
                Response.Write(cl);
                Response.Write("
"); } return ""; } } }

OUTPUT:

WHATEVER YOU DO
DO IT WELL.
WHAT WE THINK
WE BECOME.

Monday, April 19, 2021

LINQ List

ASP.NET Core LINQ Demo for List

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace LINQArray.Controllers
{
    public class HomeController : Controller
    {
        public async Task Index()
        {
            List fruits = new List()
            {
                new Fruit{ Id=1, Name="Apple",Price=23, Units=9},
                new Fruit{ Id=2, Name="Guava",Price=13, Units=4},
                new Fruit{ Id=3, Name="Orange",Price=22, Units=7},
                new Fruit{ Id=4, Name="Pear",Price=25, Units=8},
            };
            IEnumerable _fruits = from f in fruits select f;
            foreach (var fruit in _fruits)
            {
               await Response.WriteAsync(fruit.Id.ToString() + ", " + fruit.Name + ", " + fruit.Price.ToString() + ", " + fruit.Units.ToString() + "
"); } return string.Empty; } } class Fruit { public int Id { get; set; } public string Name { get; set; } public int Price { get; set; } public int Units { get; set; } } }

Updated on 6 July 2023

LINQ Array

Example - ASP.NET Core With LINQ Array
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace LINQArray.Controllers
{
    public class HomeController : Controller
    {
        public async Task Index()
        {
            string[] names = new string[] { "Chandan", "Darsh", "Darpan", "Shiva", "Ajeet" };
            
            IEnumerable Names = from name in names select name;
            //IEnumerable Names = from name in names where name.Length == 5 select name;
            //IEnumerable Names = from name in names where name.Contains("an") select name;
            //IEnumerable Names = from name in names orderby name select name;
            //IEnumerable Names = from name in names orderby name descending select name;
            //IEnumerable Names = from name in names orderby name select name.ToUpper();
            
            foreach (var name in Names)
            {
                await Response.WriteAsync("<h1>" + name + "</h1>");
            }
            return string.Empty;
        }
    }
}
OUTPUT:


Updated on 6 July 2023

Hot Topics