CS4540 Special Topics in Web Development LINQ to Objects Chengyu Sun California State University, Los Angeles
C# Language Features Used in LINQ Implicit typing using var Anonymous types and tuples Extension methods Delegates and lambda expressions
Example: Find Data in Array List in the names that start with "J" in alphabetic order var results = new List<string>(); foreach (var name in names) if (name.StartsWith("J")) results.Add(name); results.Sort();
Using LINQ (Language Integrated Query) var results = from name in names where name.StartsWith("J") orderby name select name; OR var results = names .Where(name => name.StartsWith("J")) .OrderBy(name => name) .Select(name => name);
About LINQ … Query and transform data using SQL-like syntax Simplify coding Standardize data access across objects, relational data and XML data LINQ to Objects works on anything that implements IEnumerable, i.e. arrays and all collections
… About LINQ Query result is something that implements IEnumerable Using var is usually necessary
LINQ vs SQL LINQ is for objects while SQL is for relational data (i.e. rows and column) Object Collection from name in names where name.StartsWith("J") orderby name select name; Object Method OrderBy and projection on the whole object or some properties
Query Syntax vs. Method Syntax They are equivalent (query expressions are eventually translated into extension methods) Query syntax tends to be more concise and readable Query syntax does not cover all extension methods (i.e. sometimes you have to use method syntax)
Query Execution Deferred execution: LINQ queries not executed until the iteration of the results Getting the latest result Repeated execution Immediate execution can be done by calling ToArray() or ToList() Query operators that return a single value (e.g. Count()) also execute immediately
Basic LINQ Query Syntax An arbitrary name for an item in the collection The name of the collection from <item> in <collection> where <conditions> select <projection> Conditions like in SQL but expressed using C# operators and methods The whole object or some of its properties (using anonymous type or tuple syntax)
Standard Query Operators Implemented as extension methods in System.Linq.Enumerable Only some of the extension methods have equivalent query expression
The Company Example Employee Project Company
Simple Selection Q1. Find the employees whose last names are Doe With order by With projection With duplicate removal
The Difference Between Objects and Relational Data Q2. find the leader of the project Blue SQL: JOIN LINQ: ??
Joins Q3. Find Jane Doe's supervisor Query syntax: from <item1> in <collection1> join <item2> in <collection2> on <key1> equals <key2> Method syntax: ??
Set Operations Q4. Find the employees who are on both project Firestone and project Blue Set operations: intersect, except, union Element operations
Aggregation Functions 5. Find the number of employees hired in 2015 Aggregation functions: count, sum, average, min, max
GroupBy in LINQ … 6. Group the employees by the year in which they were hired Unlike in SQL, GroupBy in LINQ only creates groups without requiring aggregation Each group is represented by an IGrouping<TKey, Telements>
… GroupBy in LINQ Query syntax: from <item> in <collection> group <element> by <key> Method syntax: ??
Simple Query Builder by Chaining Where() … Employee Search First Name Last Name Year Hired Search
… Simple Query Builder By Chaining Where() IEnumerable<Employee> results = c.Employees; if (!String.IsNullOrEmpty(firstName)) results = results.Where( e => e.FirstName == firstName); if (!String.IsNullOrEmpty(lastName)) e => e.LastName == lastName); if (!String.IsNullOrEmpty(year)) e => e.DateHired.Year == Int32.Parse(year)); results = results.Select(e => e);
Readings Pro C# 7: Chapter 12