CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections
description
Transcript of CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections
![Page 1: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/1.jpg)
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
UTPA – Fall 2012
1
![Page 2: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/2.jpg)
Objectives
• 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
![Page 3: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/3.jpg)
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!)
![Page 4: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/4.jpg)
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
![Page 5: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/5.jpg)
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
![Page 6: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/6.jpg)
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
![Page 7: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/7.jpg)
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;
![Page 8: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/8.jpg)
Display the Results
• Method call– Display (sorted, "values greater than 4, descending:");
• Method declarationpublic static void Display(IEnumerable <int> results, string header){
Console.Write("{0}", header);foreach (var element in results)
Console.Write(" {0}", element);}
8
![Page 9: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/9.jpg)
Another Example: Querying an Array Using LINQ
• To search for scores >=60
var passed = from score in scores
where score >= 60
select score;
foreach (var score in passed)
{
ListLINQresult.Items.Add(score);
}9
![Page 10: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/10.jpg)
Compare Arrays with Collections
• You must specify an arrays size• You can resize it in some languages at runtime• .Net framework generic collections gives greater
flexibility– Reusable– Reliable– Powerful– Efficient
• We are going to use the List class from this collection
10
![Page 11: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/11.jpg)
Lists
• Dynamic resizing• LINQ can be used with different types of data
sources, including lists and arrays– SQL is only used with databases
• Lists are similar to arrays but provide additional functionality:– Dynamic resizing– Provides many built-in methods– Can use LINQ queries
11
![Page 12: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/12.jpg)
Collections
• Collections do not have a fixed size• Size of a collection is increased automatically when elements
are added to it• Collections: lists, sorted lists, queues, stacks and array lists• UnTyped and typed collections• Using System.Collections
– ArrayList numbers = new ArrayList(); – numbers.Add(3);
• Using System.Colelctions.Generic– List<int> numbers = new List<int>();– numbrs.Add(3);
12
![Page 13: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/13.jpg)
Example of List Coding
string[] grades = txtEnterGrade.Text.Split(' ');
List<int> scores = new List<int>();
int numScores = grades.Length;
foreach (string grade in grades)
{
scores.Add(Convert.ToInt32(grade));
ListBoxGrades.Items.Add(grade);
}
13
![Page 14: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/14.jpg)
Example of List Coding (cont'd)
public double standardDeviation(List<int> scores, int numScores) //declaration
{int sum=0;foreach (int score in scores)
{ sum = sum + score;
}}
14
![Page 15: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/15.jpg)
Stack Operation (built-in)
Stack<string> students = new Stack<string>(); students.Push("Abbit");
students.Push("Aguero");students.Push("Castro");students.Push("Chen");students.Push("Cruz");
while (students.Count > 0) MessageBox.Show("Popped: " + students.Pop());
15
![Page 16: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/16.jpg)
Some Methods/Properties of List
• .Add – Adds to the end of the list
• .Insert – Inserts an element at the specified index
• .Clear – Removes all elements from the list
• .Remove – Removes the first occurrence of the specified value
• .Contains – Returns true if the List contains value
• .Sort
16
![Page 17: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/17.jpg)
Struct – Example
public struct Info { public string fName;
public string lName; public string Address1; public string Address2; public int zip; public string Tele; }
17
![Page 18: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/18.jpg)
List of Struct
public List <Info> friendsList = new List<Info>();
Info onePerson;
onePerson.fName=txt_fName.Text;onePerson.lName=txt_lName.Text;onePerson.Address1=txtAddr1.Text;onePerson.Address2=txtAddr2.Text;onePerson.zip=Convert.ToInt32 (txtZip.Text);onePerson.Tele=txtTele.Text;
friendsList.Add(onePerson);
18
![Page 19: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/19.jpg)
LINQ Search for a Last Name in a List
//will select every person with that last name
var foundTele = from person in friendsList
where person.lName==txtSearchName.Text
select person;
19
![Page 20: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/20.jpg)
Display the Selected Names and Telephone Numbers
foreach (var person in foundTele)
{
display +=person.fName+" "+person.lName+"\t";
display += person.Tele + "\n";
}
MessageBox.Show(display, "Names and Telephone Nos. Persons searched:");
20
![Page 21: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/21.jpg)
Select Those with GPA >+
var foundGPA =
from person in friendsList
where person.GPA>=Convert.ToSingle(txtSearchGPA.Text)
select person;
21
![Page 22: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/22.jpg)
Display
foreach (var person in foundGPA){ display += person.fName + " " + person.lName + "\t"; display += person.Tele + "\t"; display += Convert.ToString(person.GPA)+"\n";}MessageBox.Show(display, "Names and Telephone Nos. Persons
searched:")
22
![Page 23: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/23.jpg)
More About File Input/Output
• …
23
![Page 24: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/24.jpg)
Obtaining File Name From Chooser
OpenFileDialog fDialog = new OpenFileDialog();
if (fDialog.ShowDialog() == DialogResult.OK)
{
fileName = (fDialog.FileName.ToString());
MessageBox.Show(fileName);
}
24
![Page 25: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/25.jpg)
Reading From a FileTextReader ofile = new StreamReader(fileName);while (ofile.Peek()!=-1){ string oneline = ofile.ReadLine(); MessageBox.Show(oneline,"Reading From File.."); string[] items = oneline.Split(','); onePerson.fName = items[0]; onePerson.lName = items[1]; onePerson.GPA = Convert.ToSingle(items[3]); onePerson.Tele = items[2]; friendsList.Add(onePerson);}ofile.Close(); 25
![Page 26: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/26.jpg)
Writing to the File
StreamWriter outfile = new StreamWriter(fileName);
foreach (Info person in friendsList)
outfile.WriteLine(person.fName+","+person.lName+","+person.Tele+","+Convert.ToString(person.GPA));
outfile.Close();
26
![Page 27: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/27.jpg)
Example of Employees
public class Employee
{
public string FirstName;
public string LastName;
public decimal monthlySalaryValue;
}
27
![Page 28: CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections](https://reader036.fdocuments.us/reader036/viewer/2022062409/56814fe1550346895dbda9d9/html5/thumbnails/28.jpg)
Example of Employees (cont'd)public class LINQwithArray{
Employee [] employee_array; LINQwithArray(){
// … initializing arrays}public void LINQ_query(){
var nameSorted = (from e in employee_array where e.MonthlySalary >= 4000 orderby e.LastName, e.FirstName select e).Distinct();
if (!nameSorted.Any())Console.WriteLine("not found\n");
}}
28