Download presentation
Presentation is loading. Please wait.
1
LINQ .NET Language Integrated Query
Dr. Victor Matos Cleveland State University April 2018
2
What is LINQ Language Integrated Query (LINQ, pronounced "link") is a Microsoft .NET technology that adds data querying capabilities to .NET languages. Query expressions are written in a declarative query syntax. By using query syntax, you can perform filtering, ordering, and grouping operations on data sources with a minimum of code. LINQ query expressions, are similar to SQL statements, and can be used to conveniently extract and process data from arrays, enumerable classes, XML documents, relational databases, and third-party data sources (web services).
3
What is LINQ .NET App (C#, C++, Visual Basic, …) LINQ Query Arrays, Enumerable classes, XML documents, Relational databases, Web services VAR ….
4
General Structure of a LINQ Expression
var query = from s in names where s.Length == 5 orderby s select s.ToUpper(); var is a dynamic container that accepts any type of data. from clause defines the range of each datarow/object to be examined. In this sample, s is an item in a collection called names. where clause is a filter. It indicates the condition that items s must satisfy in order to be selected. In this example, s is chosen to be part of the output if its length is five characters. orderby sorts the selected rows (optional clause) select enumerates the projected output fields (here, all of s).
5
General Structure of a LINQ Expression
var expr defines an anonymous variable resulting from evaluating a LINQ query expression. A query expression operates on one or more information sources by applying one or more query operators. var expressions use three of the standard query operators: Where, OrderBy, and Select. Observe the Where clause in C# is phrased using C# syntax (uses &&, ||, double-quoted-strings).
6
Anonymous Types in .NET Anonymous types allow data types to encapsulate (on-the-fly) a set of properties (fields) into a single object without having to first explicitly define a type. For instance, produce on-the-fly a new type that only takes two fields from an existing class. Say, list the SSN and Salary of an Employee object, instead all of its data. This is an important feature for the SQL-like LINQ feature that is integrated into C#. Since anonymous types do not have a named typing, they must be stored in dynamic variables declared using the var keyword, telling the C# compiler to use type inference for the variable.
7
LINQ Operators Operator Type Operator Name Aggregation
Aggregate, Average, Count, LongCount, Max, Min, Sum Conversion Cast, OfType, ToArray, ToDictionary, ToList, ToLookup, ToSequence Element DefaultIfEmpty, ElementAt, ElementAtOrDefault, First, FirstOrDefault, Last, LastOrDefault, Single, SingleOrDefault Equality EqualAll Generation Empty, Range, Repeat Grouping GroupBy Joining GroupJoin, Join Ordering OrderBy, ThenBy, OrderByDescending, ThenByDescending, Reverse Partitioning Skip, SkipWhile, Take, TakeWhile Quantifiers All, Any, Contains Restriction Where Selection Select, SelectMany Set Concat, Distinct, Except, Intersect, Union
8
Example 01A – Using Plain C# Retrieve from a given string array the names having five characters.
//data source string[] names = { "Burke", "Connor", "Frank", "Everett", "Albert", "George", "Harris", "David", "Alfonzo" }; //prepare result container - put selected names in a dynamic list List<string> fiveLetterNames = new List<string>(); //(brute force search) visit each array cell selecting five-letter names foreach (string str in names) { if (str.Length == 5) fiveLetterNames.Add(str); } //sort selected items fiveLetterNames.Sort(); //show results foreach(string s in fiveLetterNames) Console.WriteLine(s);
9
Example 01B – Using LINQ Query Syntax Retrieve from a given string array the names having five characters string[] names = { "Burke", "Connor", "Frank", "Everett", "Albert", "George", "Harris", "David", "Alfonzo" }; var query = from s in names where s.Length == 5 orderby s select s.ToUpper(); foreach (string item in query) Console.WriteLine(item);
10
LINQ Coding Style Any LINQ query that can be expressed by using query syntax can also be expressed by using method syntax. However, in most cases query syntax is more readable and concise. For example, the previous example could be re-written using method syntax as follows var result2 = names.Where(s => s.Length == 5) .OrderBy(s => s) .Select(s => s.ToUpper()); NOTE: Statements of the form 𝑠=>𝑓(𝑠) are called Lambda Expressions.
11
Example02 (Using Method Syntax) Retrieve names starting with 'A' or 'B'
string[] names = { "Burke", "Connor", "Frank", "Everett", "Albert", "George", "Harris", "David", "Alfonzo" }; var AorBFirst = names.Where(s => s[0]=='A' || s[0] =='B') .OrderByDescending(s=>s) .Select(s => s.ToUpper()); foreach (string str in AorBFirst) Console.WriteLine(str);
12
Example03. Select strings ending on a given word
List<string> msg = new List<string>() {"hello world", "hello LINQ", "adios LINQ" }; var items = from s in msg where s.EndsWith("LINQ") select s; foreach (var item in items) Console.WriteLine(item);
13
Example 04A Retrieving data from an XML dataset
XElement books = <book> <title>Don Quixote</title> <author>Miguel de Cervantes</author> </book> <title>Romeo and Juliet</title> <author>William Shakespeare</author> <title>The Game of Thrones</title> <author>George R.R. Martin</author> </books>"); var titles = from book in books.Elements("book") where book.Element("author").ToString() == "Miguel de Cervantes" select book.Element("title"); foreach (var title in titles) Console.WriteLine(title.Value);
14
Example 04B Retrieving data from a JSON dataset
/*** Assume the serialized JSON dataset is as follows (see Appendix) **** [ {"Title":"The Game of Thrones","Author":"George R.R. Martin"}, {"Title":"Don Quixote","Author":"Miguel de Cervantes"}, {"Title":"Romeo and Juliet","Author":"William Shakespeare"} ] *************************************************************************/ JavaScriptSerializer ser = new JavaScriptSerializer(); List<Book> lstBook = new List<Book>(Book.GetListBooks()); string jsonBooks = ser.Serialize(lstBook); var varBooks = from b in ser.Deserialize<List<Book>>(jsonBooks) orderby b.Title select b; foreach (var b in varBooks) Console.WriteLine(b);
15
Westeros Heroes & Houses Memory Database
All Hero attributes are public. Lazy definition! House is defined as a common C# class (private attributes, constructors, properties, user-defined methods)
16
Heroes Next queries will use the following class.
public class Hero { public int id; // CAUTION: observe that all attributes are defined PUBLIC (Lazy!) public string name; public string houseId; public string sex; public static List<Hero> GetHeroesList() // Compact version – list uses immediate anonymous objs List<Hero> westerosHeroes = new List<Hero>() new Hero { id = 101, name = "Arya Startk", houseId = "STA", sex = "F" }, new Hero { id = 102, name = "Jon Snow", houseId = "STA", sex = "M" }, new Hero { id = 103, name = "Sansa Stark", houseId = "STA", sex = "F" }, new Hero { id = 104, name = "Bran Stark", houseId = "STA", sex = "M" }, new Hero { id = 201, name = "Cersei Lannister", houseId = "LAN", sex = "F" }, new Hero { id = 202, name = "Jaime Lannister", houseId = "LAN", sex = "M" }, new Hero { id = 301, name = "Daenerys Targaryen", houseId = "TAR", sex = "F" }, new Hero { id = 302, name = "Missandei", houseId = "TAR", sex = "F" }, new Hero { id = 401, name = "Yara Greyjoy", houseId = "GRE", sex = "F" }, new Hero { id = 402, name = "Theon Greyjoy", houseId = "GRE", sex = "M" }, new Hero { id = 403, name = "Euron Greyjoy", houseId = "GRE", sex = "M" }, }; return westerosHeroes; }
17
House Great houses of Westeros.
class House { //private data members private string houseId; private string houseName; private string houseLocation; //properties public string HouseId { get => houseId; set => houseId = value; } public string HouseName { get => houseName; set => houseName = value; } public string HouseLocation { get=>houseLocation; set=>houseLocation=value; } //constructors public House(){} public House(string houseIdValue, string houseNameValue, string houseLocationValue){ HouseId = houseIdValue; HouseName = houseNameValue; HouseLocation = houseLocationValue; } //user-defined methods public override string ToString() { return string.Format($"House [ ID {HouseId} Name {HouseName} Loc {houseLocation}"); } //return a list of the Great Westeros Houses public static List<House> GetGreatHousesList() return new List<House>() { new House("STA", "House Stark", "Winterfel-The North"), new House("LAN", "House Lannister", "Casterly Rock-Westerlands"), new House("GRE", "House Greyjoy", "Salt Castle-Iron Islands"), new House("TAR", "House Targaryen", "Dragonstone-Crownlands"), };
18
Westeros data Hero House id name houseId sex 101 Arya Startk STA F 102
Jon Snow M 103 Sansa Stark 104 Bran Stark 201 Cersei Lannister LAN 202 Jaime Lannister 301 Daenerys Targaryen TAR 302 Missandei 401 Yara Greyjoy GRE 402 Theon Greyjoy 403 Euron Greyjoy House HouseId Name Location STA House Stark Winterfel-The North LAN House Lannister Casterly Rock-Westerlands GRE House Greyjoy Salt Castle-Iron Islands TAR House Targaryen Dragonstone-Crownlands
19
Example 05 List all Westeros Heroes.
var heroes = from h in Hero.GetHeroesList() select h; foreach (Hero h in heroes) { Console.WriteLine($"{h.id} {h.name, -20} {h.houseId}"); }
20
Example 06 List heroes from the House Stark ('STA').
var heroes = from h in Hero.GetHeroesList() where (h.houseId == "STA") select h; foreach (Hero h in heroes) Console.WriteLine($"{h.id} {h.name,-20} {h.houseId}");
21
Example 07 Find the id and name of female heroes from the House Stark
var heroes = from h in Hero.GetHeroesList() where (h.houseId == "STA") && (h.sex == "F") select new { h.id, h.name }; foreach (var h in heroes) Console.WriteLine($"{h.id} {h.name,-20} ");
22
Example 08 List Stark Heroes whose name contains the letter "a".
//Heroes are listed in alphabetic order var heroes = from h in Hero.GetHeroesList() where (h.houseId == "STA") && (h.name.Contains("a")) orderby h.name select new { h.houseId, h.name }; foreach (var h in heroes) Console.WriteLine($"{h.houseId} {h.name,-20} ");
23
Example 08 List Heroes from either House Stark or House Targaryen.
//Heroes are listed in alphabetic order var heroes = from h in Hero.GetHeroesList() where (h.houseId == "STA") || (h.houseId=="TAR") orderby h.name select new { h.houseId, h.name }; foreach (var h in heroes) Console.WriteLine($"{h.houseId} {h.name,-20} ");
24
Example 09 List great houses of Westeros (descending order).
//houses are listed in descending alphabetic order var houses = from h in House.GetGreatHousesList() orderby h.HouseName descending select h; foreach (House h in houses) Console.WriteLine($"{h.HouseId} {h.HouseName,-20} " + $"{h.HouseLocation}");
25
Example 10 List houses located in either the Crownlands or the Wersterlands
var houses = from h in House.GetGreatHousesList() where (h.HouseLocation.Contains("Crownlands") || (h.HouseLocation.Contains("Westerland"))) select h; foreach (House h in houses) Console.WriteLine($"{h.HouseId} {h.HouseName,-20} " + $"{h.HouseLocation}");
26
Example 11 Combine Hero and House data
Example 11 Combine Hero and House data. Show hero's name and house location. //join the Hero and House collections using common key (HouseId) var housePerson = from h in House.GetGreatHousesList() from p in Hero.GetHeroesList() where (h.HouseId == p.houseId) orderby p.name select new { p.name, h.HouseLocation }; foreach (var ph in housePerson) Console.WriteLine($"{ph.name, -20} {ph.HouseLocation} ");
27
Example 12 Retrieve the name of female Dragonstone heroes.
var housePerson = from h in House.GetGreatHousesList() from p in Hero.GetHeroesList() where (h.HouseId == p.houseId) && (p.sex == "F") && (h.HouseLocation.Contains("Dragonstone")) orderby p.name select new { p.name }; foreach (var ph in housePerson) Console.WriteLine($"{ph.name,-20} ");
28
Example 13 Examine the Hero collection
Example 13 Examine the Hero collection. Tell how many heroes by house are there. //example of a group-by query var heroGroups = from h in Hero.GetHeroesList() group h by h.houseId into hGroup select new { HouseId = hGroup.Key, HouseCount = hGroup.Count() }; foreach(var g in heroGroups) Console.WriteLine( g);
29
Example 14 Transfer LINQ results to common
Example 14 Transfer LINQ results to common .NET collections (array & List<>) //saving LINQ dynamic answer into a .NET List<> and Array var houses = from h in House.GetGreatHousesList() orderby h.HouseName select h; List<House> housesList = houses.ToList<House>(); House[] housesArray = houses.ToArray<House>(); foreach(House h in housesArray) Console.WriteLine( h );
30
LINQ to SQL Databases NORTHWIND DB Northwind Traders
database is a sample database included in the Microsoft Office suite. The database contains fictitious sales data for Northwind Traders, which imports and exports specialty foods from around the world. Download from:
31
Example 15 List customers in Torino, Rio de Janeiro & Barquisimeto.
//connection string: using SQL Express & relax authenticat. Northwind db = new Source=.\SQLEXPRESS;" Catalog=Northwind;" Security=SSPI;"); var custs = from c in db.Customers where c.City == "Rio de Janeiro" || c.City == "Barquisimeto" || c.City == "Torino" select c; foreach (var cust in custs) Console.WriteLine($"{cust.CompanyName, -20} " + $"{cust.City, -20}");
32
Example 16 List products bought by customers in .
var articlesPurchased = from c in db.Customers from o in db.Orders from d in db.OrderDetails from p in db.Products where (c.CustomerID == o.CustomerID) && (o.OrderID == d.OrderID) && (d.ProductID == p.ProductID) && (c.City == "Torino") select new { c.CompanyName, p.ProductName }; foreach(var ap in articlesPurchased) Console.WriteLine($"{ap.CompanyName, -20} " $"{ap.ProductName}");
33
Example 17 Processing data from text files
Potter, Harry Granger, Hermione Weasley, Ron Weasley, Ginny Dobby Snape, Severus Dumbledore, Albus Assume the text file c:\temp\hogwarts.txt contains the records listed on the right box → // read data from disk file, store rows inside array string[] fileA = foreach (string s in fileA) Console.WriteLine(s); // Find the matching people string nameMatch = "Weasley"; var tempQuery1 = from name in fileA let n = name.Split(',', ' ') where n[0] == nameMatch orderby name select name; foreach (string s in tempQuery1) Console.WriteLine(s);
34
Example 18 Processing textual data. Find and tally a word. 1 of 2
string text = @"A long time ago, in a galaxy far, far away... It is a period of civil war. Rebel spaceships, striking from a hidden base, have won their first victory against the evil Galactic Empire. During the battle, Rebel spies managed to steal secret plans to the Empire's ultimate weapon, the Death Star, an armored space station with enough power to destroy an entire planet. Pursued by the Empire's sinister agents, Princess Leia races home aboard her starship, custodian of the stolen plans that can save her people and restore freedom to the galaxy.... ";
35
Example 18 Processing textual data. Find and tally a word. 2 of 2
//this is the word to llok for in the text string searchTerm = "empire"; //Convert the long string text into an array of words (use separators) string[] source = text.Split( new char[] { '.', '?', '!', ' ', ';', ':', ',', '\'' }, StringSplitOptions.RemoveEmptyEntries); // Create the query. Use ToLowerInvariant to match "empire" and "Empire" var matchQuery = from word in source where word.ToLower() == searchTerm.ToLower() select word; // Count the matches, which executes the query. int wordCount = matchQuery.Count(); Console.WriteLine($"\n\n{wordCount} occurrences(s) of the " + $"search term \"{searchTerm}\" were found.");
36
On-Line Resources Microsoft Channel9 – The LINQ Project by Lucca Bolognese (Video, Intermediate, 53 min) Microsoft Virtual Academy – C# Fundamentals for Absolute Beginners by Bob Tabor (Video, beginner level, 24 min.) Microsoft Virtual Academy - Language Integrated Query (LINQ) Instructor(s): Tony Sneed (Video, advanced level, 53 minutes) XML documents ADO.NET Entity Framework .NET collections, files, strings and so on.
37
Appendix A The Book class is used in Example04B
class Book { public string Title { get; set; } public string Author { get; set; } public static List<Book> GetListBooks() return new List<Book>() new Book {Author= "George R.R. Martin", Title="The Game of Thrones" }, new Book {Author= "Miguel de Cervantes", Title="Don Quixote" }, new Book {Author= "William Shakespeare", Title="Romeo and Juliet" }, }; } public override string ToString() return string.Format($"Book[ Title= {Title} Author={Author}");
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.