CSCI 3328 Object CSCI 3328 Object Oriented Programming in Oriented Programming in C# C# Chapter 8: LINQ and Chapter 8: LINQ and Generic Collections Generic Collections 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX 78539 [email protected]
28
Embed
CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
CSCI 3328 Object Oriented CSCI 3328 Object Oriented Programming in C# Programming in C#
Chapter 8: LINQ and Generic Chapter 8: LINQ and Generic CollectionsCollections
• In this chapter, you will:– Become familiar with the basic concept of LINQ– Learn how to use LINQ to query an array– Learn how to sort an array using LINQ– Learn how to manipulate collections (e.g., List) by
LINQ
2
LINQ
• Language Integrated Query (LINQ)• Old way:
– Structured Query Language (SQL)– Queries are written in string and passed to database
which interprets the string, processes the request, and returns the results
• LINQ allows a programming language to submit queries directly to a wide range of data sources (not just databases!)
LINQ (cont'd)
• LINQ is a logical extension of querying and manipulating data in databases
• In C#, you must include namespace System.Linq– using System.Linq
• Data sources– Arrays– Collections– Files
• Query expression is similar to SQL
4
Writing an LINQ Query
• A LINQ query begins with a from clause– After from clause, specify a range variable and the
data source to query– The range variable represents each item in the data
source (much like foreach)– E.g., passed = from score in scores
• The where clause gives a condition for the search and evaluates to true or false – If true, the value is selected
• The select clause determines what value appears in the results
• Do not forget semicolon (;) at the end
Querying an Array Using LINQ
• var filtered = from value in values
where value > 4
select value;
• var sorted = from value in filtered
orderby value
select value; default: ascending
Querying an Array Using LINQ (cont'd)
• var sorted = from value in filtered
orderby value descending
select value;
• var sorted = from value in values
where (value > 4)
orderby value descending
select value;
Display the Results
• Method call– Display (sorted, "values greater than 4, descending:");