ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Enterprise Application Development
    EC-332
    Progress0 / 37 topics
    Topics
    1. Overview of Enterprise Application Development: Microsoft technology history2. Introduction to .NET and its architecture3. Concept of MSIL, CLR, CLS, CTS4. Introduction to .NET framework: Managed and Unmanaged Code5. .Net Assembly6. Introduction to C# fundamentals7. Boxing and Unboxing8. Implementing multi-tier architecture9. Introduction to ADO.Net: SQL Injection, parameterized queries10. Usage of data set, Data adapter and command builder in disconnected model11. Introduction to delegate: Multicast delegates12. Introduction to windows forms13. HTML14. Introduction to javascript: javascript and its data types, variables, functions15. Debugging javascript using Firebug16. Introduction to various object models: Browser's Object (BOM), Document Object Model17. Introduction to Jquery: Jquery effects18. Introducing LINQ: LINQ to Objects, LINQ to SQL19. Query syntax, Operations (projection, filtering and join) using Linq Queries20. Introduction to ADO.NET entity framework: The entity data model, CSDL21. Eager vs lazy loading, POCO classes, DBContext API22. Querying entity data models23. Introduction to ASP.NET MVC24. MVC application structure, Controllers overview25. Action Methods, Parameterized action methods26. Introduction to razor syntax27. Code expressions, Code Blocks, Implicit Vs Explicit Code Expression28. Data annotations, Client and Server Side Validation29. Validation and model binding, Validation and model state30. MVC Membership, Authorization and security31. Introduction to service-oriented architecture: SOAP, WSDL32. Service contract, Data contract, XML, WCF bindings33. ABC of WCF, Restful services34. Consuming rest services (CRUD operations) using Jquery AJAX and JSON35. Introduction to web API36. Example of web API using CRUD Example37. MVC routing
    EC-332›Query syntax, Operations (projection, filtering and join) using Linq Queries
    Enterprise Application DevelopmentTopic 19 of 37

    Query syntax, Operations (projection, filtering and join) using Linq Queries

    8 minread
    1,434words
    Intermediatelevel

    LINQ Query Syntax: Operations (Projection, Filtering, and Join)

    LINQ (Language Integrated Query) allows you to query data from various sources using a consistent syntax, which can be applied to objects, collections, databases, XML, and more. LINQ supports multiple types of operations, including projection, filtering, and joining, making it a powerful tool for working with data.

    In this explanation, we'll focus on query syntax and how to perform projection, filtering, and joining using LINQ queries.


    1. Query Syntax Overview

    LINQ allows you to write queries using query syntax (which is similar to SQL) or method syntax (using LINQ extension methods). The query syntax provides a more SQL-like approach, which can be easier to understand for people with a background in database query languages.

    Here's the general structure of a LINQ query in query syntax:

    var query = from variable in collection
                where condition
                select variable;
    
    • from variable in collection: Defines the data source (like a list, array, or database table).
    • where condition: Filters the data based on a specified condition (optional).
    • select variable: Projects or selects the desired data (optional).

    2. Projection in LINQ Queries

    Projection is the operation that transforms data into a new shape. In LINQ, you use select to project the elements of a collection into a new format, which can include selecting specific fields or creating new objects.

    Example of Projection:

    Imagine you have a collection of Person objects, and you want to project just the names and ages of the people into a new format.

    using System;
    using System.Linq;
    using System.Collections.Generic;
    
    class Program
    {
        public class Person
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }
    
        static void Main()
        {
            // Sample list of people
            List<Person> people = new List<Person>
            {
                new Person { Name = "John", Age = 25 },
                new Person { Name = "Jane", Age = 30 },
                new Person { Name = "Mike", Age = 35 }
            };
    
            // Projection using query syntax
            var projectedData = from person in people
                                select new { person.Name, person.Age };
    
            foreach (var data in projectedData)
            {
                Console.WriteLine($"Name: {data.Name}, Age: {data.Age}");
            }
        }
    }
    

    In this example:

    • Projection occurs through the select new { person.Name, person.Age } part of the query, which creates anonymous objects containing only the Name and Age properties.

    3. Filtering in LINQ Queries

    Filtering is the process of selecting only those elements that meet a certain condition. You can filter elements in LINQ using the where clause.

    Example of Filtering:

    Suppose you want to filter the list of people to include only those who are older than 30.

    using System;
    using System.Linq;
    using System.Collections.Generic;
    
    class Program
    {
        public class Person
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }
    
        static void Main()
        {
            // Sample list of people
            List<Person> people = new List<Person>
            {
                new Person { Name = "John", Age = 25 },
                new Person { Name = "Jane", Age = 30 },
                new Person { Name = "Mike", Age = 35 }
            };
    
            // Filtering using query syntax
            var filteredPeople = from person in people
                                 where person.Age > 30
                                 select person;
    
            foreach (var person in filteredPeople)
            {
                Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
            }
        }
    }
    

    In this example:

    • The where clause filters the data to include only people whose Age is greater than 30.

    4. Joining in LINQ Queries

    Joining is used when you need to combine data from two different collections (e.g., tables, lists) based on a common key. LINQ supports multiple types of joins, such as inner joins and group joins.

    Example of Inner Join:

    Let's say you have two collections: one for Persons and another for Orders. You want to join the two collections to find out which orders were made by which person.

    using System;
    using System.Linq;
    using System.Collections.Generic;
    
    class Program
    {
        public class Person
        {
            public int PersonId { get; set; }
            public string Name { get; set; }
        }
    
        public class Order
        {
            public int OrderId { get; set; }
            public int PersonId { get; set; }
            public string Product { get; set; }
        }
    
        static void Main()
        {
            // Sample list of people
            List<Person> people = new List<Person>
            {
                new Person { PersonId = 1, Name = "John" },
                new Person { PersonId = 2, Name = "Jane" }
            };
    
            // Sample list of orders
            List<Order> orders = new List<Order>
            {
                new Order { OrderId = 101, PersonId = 1, Product = "Laptop" },
                new Order { OrderId = 102, PersonId = 2, Product = "Smartphone" },
                new Order { OrderId = 103, PersonId = 1, Product = "Tablet" }
            };
    
            // Inner join using query syntax
            var joinQuery = from person in people
                            join order in orders on person.PersonId equals order.PersonId
                            select new { person.Name, order.Product };
    
            foreach (var item in joinQuery)
            {
                Console.WriteLine($"{item.Name} bought {item.Product}");
            }
        }
    }
    

    In this example:

    • Join is performed between the Person and Order collections on the PersonId field using the join keyword.
    • The result is a projection that includes both the person's name and the product they bought.

    Output:

    John bought Laptop
    Jane bought Smartphone
    John bought Tablet
    

    Types of Joins in LINQ:

    1. Inner Join: Combines elements from both collections where there is a match.
    2. Left Join (DefaultIfEmpty): Combines elements from the left collection with matching elements from the right collection. If no match is found, the right collection's elements are null.
      var leftJoin = from person in people
                     join order in orders on person.PersonId equals order.PersonId into orderGroup
                     from order in orderGroup.DefaultIfEmpty()
                     select new { person.Name, OrderProduct = order?.Product ?? "No Orders" };
      
    3. Group Join: Returns a sequence of groups, where each group contains elements from the right collection that match the corresponding left element.
      var groupJoin = from person in people
                      join order in orders on person.PersonId equals order.PersonId into orderGroup
                      select new { person.Name, Orders = orderGroup };
      

    5. Combining Operations: Projection + Filtering + Join

    You can combine multiple operations in a single LINQ query. For example, you might want to join two collections, filter the results based on a condition, and then project the result.

    Example of Combined Operations:

    using System;
    using System.Linq;
    using System.Collections.Generic;
    
    class Program
    {
        public class Person
        {
            public int PersonId { get; set; }
            public string Name { get; set; }
        }
    
        public class Order
        {
            public int OrderId { get; set; }
            public int PersonId { get; set; }
            public string Product { get; set; }
        }
    
        static void Main()
        {
            // Sample list of people
            List<Person> people = new List<Person>
            {
                new Person { PersonId = 1, Name = "John" },
                new Person { PersonId = 2, Name = "Jane" },
                new Person { PersonId = 3, Name = "Mike" }
            };
    
            // Sample list of orders
            List<Order> orders = new List<Order>
            {
                new Order { OrderId = 101, PersonId = 1, Product = "Laptop" },
                new Order { OrderId = 102, PersonId = 2, Product = "Smartphone" },
                new Order { OrderId = 103, PersonId = 1, Product = "Tablet" }
            };
    
            // Combine projection, filtering, and join
            var combinedQuery = from person in people
                                join order in orders on person.PersonId equals order.PersonId
                                where person.Name.StartsWith("J")
                                select new { person.Name, order.Product };
    
            foreach (var item in combinedQuery)
            {
                Console.WriteLine($"{item.Name} bought {item.Product}");
            }
        }
    }
    

    In this combined query:

    • We join the people and orders collections on the PersonId.
    • We filter the results to only include people whose names start with the letter "J".
    • We project the result to show the person's name and the product they bought.

    Output:

    John bought Laptop
    John bought Tablet
    Jane bought Smartphone
    

    Conclusion

    In LINQ, you can use query syntax to perform various operations on data such as:

    • Projection: Transforming data into a new format (e.g., selecting specific fields or creating new objects).
    • Filtering: Selecting data that meets a certain condition.
    • Joining: Combining data from two or more collections based on a common key.

    By using LINQ, you can write cleaner, more readable code for querying and manipulating data in C#.

    Previous topic 18
    Introducing LINQ: LINQ to Objects, LINQ to SQL
    Next topic 20
    Introduction to ADO.NET entity framework: The entity data model, CSDL

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time8 min
      Word count1,434
      Code examples0
      DifficultyIntermediate