10.1-LINQ

File Location

  1. Right click on your solution

  2. Go to Add > New Project and select Console App (.NET Framework)

  3. Name it DateTime

Discussion

LINQ or Language-Integrated Query is a powerful query language used with C# to query different data sources. LINQ is a great way to interact with your future databases.

LINQ is a query language that works with multiple languages other than C#. SQL is a query language used to save and retrieve data from a database. Similarly, LINQ is a query syntax used to save and retrieve data from different data sources like collections, databases, XML, and web services.

LINQ can be used to simplify cumbersome code that foreach and for loops can add sometimes. Let's compare. Let's make an array of employees and perform the same functions with a foreach loop and then do the same with a LINQ query.

Using a foreach loop

    class Program
    {
        static void Main(string[] args)
        {
            Employee[] employeeArray = {
            new Employee() { EmployeeID = 1, EmployeeName = "John", Age = 38 },
            new Employee() { EmployeeID = 2, EmployeeName = "Rachel",  Age = 21 },
            new Employee() { EmployeeID = 3, EmployeeName = "Bill",  Age = 25 },
            new Employee() { EmployeeID = 4, EmployeeName = "Monica" , Age = 20 },
            new Employee() { EmployeeID = 5, EmployeeName = "Ron" , Age = 31 },
            new Employee() { EmployeeID = 6, EmployeeName = "Taylor",  Age = 27 },
            new Employee() { EmployeeID = 7, EmployeeName = "Rob",Age = 29  },
            };

            Employee[] employees = new Employee[10];
            int i = 0;

            foreach (Employee emp in employeeArray)
            {
                if (emp.Age > 25 && emp.Age < 40)
                {
                    employees[i] = emp;
                    i++;
                }
            }
        }
    }

    class Employee
    {
        public int EmployeeID { get; set; }
        public string EmployeeName { get; set; }
        public int Age { get; set; }
    }

The above code will grab all the employees whose age is between 25 and 40.

Now with a LINQ query and delegate

    delegate bool FindEmployee(Employee emp);

    class StudentExtension
    {
        public static Employee[] where(Employee[] empArray, FindEmployee del)
        {
            int i = 0;
            Employee[] result = new Employee[10];
            foreach (Employee emp in empArray)
                if (del(emp))
                {
                    result[i] = emp;
                    i++;
                }
            return result;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Employee[] employeeArray = {
            new Employee() { StudentID = 1, EmployeeName = "John", Age = 38 } ,
            new Employee() { StudentID = 2, EmployeeName = "Steve",  Age = 21 } ,
            new Employee() { StudentID = 3, EmployeeName = "Bill",  Age = 25 } ,
            new Employee() { StudentID = 4, EmployeeName = "Ram" , Age = 20 } ,
            new Employee() { StudentID = 5, EmployeeName = "Ron" , Age = 31 } ,
            new Employee() { StudentID = 6, EmployeeName = "Chris",  Age = 27 } ,
            new Employee() { StudentID = 7, EmployeeName = "Rob",Age = 29  } ,
            };

            Employee[] employees = EmployeeExtension.where(employeeArray, delegate (Employee emp)
            {
                return emp.Age > 25 && emp.Age < 30;
            });

            Console.ReadLine();
        }
    }

    class Student
    {
        public int StudentID { get; set; }
        public string StudentName { get; set; }
        public int Age { get; set; }
    }

Discussion

We have the advantage of delegate in finding employees with any criteria. You don't have to use a for loop to find employees using different criteria. For example, you can use the same delegate function to find a employee whose StudentId is 5 or whose name is Bill, as below:

    Student[] students = StudentExtension.where(studentArray, delegate(Student std) {
        return std.StudentID == 5;
    });


    Student[] students = StudentExtension.where(studentArray, delegate(Student std) {
        return std.StudentName == "Bill";
    });

We just need the loop to loop through the collection but not to identify criteria.

Lambda Expression

You can make your code even more compact and readable with the lambda expression =>. Lambda is a great resource with LINQ queries to get the results you want in a single statement.

The example below shows how you can use LINQ query with lambda to find a particular employee(s) from the employee collection.

Student[] oldStudents = studentArray.Where(s => s.Age > 30).ToArray();

Student billStudents = studentArray.Where(s => s.StudentName == "Bill").FirstOrDefault();

With this expression you can totally get rid of delegate and your StudentExtension class to get the information you need. Way less code and just as powerful. To print the information to the console you would still need a forloop but with most of your later applications, you won't need to print everything to the console.

Challenge

  • Make a list of different cars, including BMW's and Hyundai's, with a price range from $8,000 - $30,000.

  • Make sure to make a class with corresponding properties.

  • Using LINQ queries

    • Find all the BMW's

    • Find all the cars less than $10,000

    • Find all the cars that cost less than $15,000 and are Hyundai's.

Answers

Optional Reading

Learn more about LINQ.

Learn more about lambda expressions.

Last updated