ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalEC-332Linq Query Operations
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    EC-332

    Enterprise Application Development

    Progress0 / 37 done
    Topics37
    1Microsoft technology history2Introduction to .NET and its architecture3Concept of MSIL, CLR, CLS, CTS
    4Managed and Unmanaged Code5.Net Assembly6Introduction to C# fundamentals7Boxing and Unboxing8Implementing multi-tier architecture
    9SQL Injection, parameterized queries10Usage of data set, Data adapter and command builder in disconnected model
    11Multicast delegates12Introduction to windows forms13HTML
    14javascript and its data types, variables, functions15Debugging javascript using Firebug
    16Browser's Object (BOM), Document Object Model
    17Jquery effects
    18LINQ to Objects, LINQ to SQL19Query syntax, Operations (projection, filtering and join) using Linq Queries
    20The entity data model, CSDL21Eager vs lazy loading, POCO classes, DBContext API22Querying entity data models23Introduction to ASP.NET MVC24MVC application structure, Controllers overview25Action Methods, Parameterized action methods26Introduction to razor syntax27Code expressions, Code Blocks, Implicit Vs Explicit Code Expression28Data annotations, Client and Server Side Validation29Validation and model binding, Validation and model state30MVC Membership, Authorization and security
    31SOAP, WSDL32Service contract, Data contract, XML, WCF bindings33ABC of WCF, Restful services34Consuming rest services (CRUD operations) using Jquery AJAX and JSON35Introduction to web API36Example of web API using CRUD Example37MVC routing
    8 min read
    Topic 19 of 37
    Topic Study Note Illustration
    19

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

    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 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 view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    8mremaining
    1.4kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Enterprise Application Development