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.

Slides:



Advertisements
Similar presentations
LINQ and Collections An introduction to LINQ and Collections.
Advertisements

Extension Methods, Anonymous Types LINQ Query Keywords, Lambda Expressions Svetlin Nakov Telerik Corporation
CSCI 3328 Object Oriented Programming in C# Chapter 9: Classes and Objects: A Deeper Look 1 Xiang Lian The University of Texas – Pan American Edinburg,
CSCI 3328 Object Oriented Programming in C# Chapter 12: Databases and LINQ 1 Xiang Lian The University of Texas – Pan American Edinburg, TX 78539
XML files (with LINQ). Introduction to LINQ ( Language Integrated Query ) C#’s new LINQ capabilities allow you to write query expressions that retrieve.
Chapter 9: Advanced Array Concepts
The University of Texas – Pan American
Extension Methods, Anonymous Types LINQ Query Keywords, Lambda Expressions Based on material from Telerik Corporation.
1 Chapter 7 – Arrays 7.1 Creating and Accessing Arrays 7.2 Using LINQ with Arrays 7.3 Arrays of Structures 7.4 Two-Dimensional Arrays 7.5 A Case Study:
Generics Collections. Why do we need Generics? Another method of software re-use. When we implement an algorithm, we want to re-use it for different types.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Hoang Anh Viet Hà Nội University of Technology Chapter 1. Introduction to C# Programming.
 Although VERY commonly used, arrays have limited capabilities  A List is similar to an array but provides additional functionality, such as dynamic.
Introduction to LINQ Chapter 11. Introduction Large amounts of data are often stored in a database—an organized collection of data. A database management.
Generics Collections. Why do we need Generics? Another method of software re-use. When we implement an algorithm, we want to re-use it for different types.
CSCI 3327 Visual Basic Chapter 13: Databases and LINQ UTPA – Fall 2011.
CSCI 3328 Object Oriented Programming in C# Chapter 5: C# Control Statement – Part II – Exercises 1 Xiang Lian The University of Texas Rio Grande Valley.
CSCI 3328 Object Oriented Programming in C# Chapter 4: C# Control Statement – Part I 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX.
Object Oriented Programming Generic Collections and LINQ Dr. Mike Spann
CSCI 3328 Object Oriented Programming in C# Chapter 6: Methods 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX 78539
CSCI 3327 Visual Basic Chapter 8: Introduction to LINQ and Collections UTPA – Fall 2011.
LINQ AND GENERIC COLLECTIONS DR. JOHN P. ABRAHAM PROFESSOR UTPA.
PROGRAMMING IN C#. Collection Classes (C# Programming Guide) The.NET Framework provides specialized classes for data storage and retrieval. These classes.
CSCI 3328 Object Oriented Programming in C# Chapter 7: Arrays 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX 78539
CSCI 3328 Object Oriented Programming in C# Chapter 9: Classes and Objects: A Deeper Look – Exercises 1 Xiang Lian The University of Texas Rio Grande Valley.
CSCI 3328 Object Oriented Programming in C# Chapter 11: Files and Streams -- Exercises 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg,
CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections – Exercises 1 Xiang Lian The University of Texas – Pan American Edinburg,
CIS 200 Test 01 Review. Built-In Types Properties  Exposed “Variables” or accessible values of an object  Can have access controlled via scope modifiers.
COMPUTER PROGRAMMING 2 ArrayLists. Objective/Essential Standard Essential Standard 3.00Apply Advanced Properties of Arrays Essential Indicator 3.02 Apply.
CSCI 3328 Object Oriented Programming in C# Chapter 12: Databases and LINQ – Exercises 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg,
IAP C# 2011 Lecture 2: Delegates, Lambdas, LINQ Geza Kovacs.
LINQ Language Integrated Query LINQ1. LINQ: Why and what? Problem Many data sources: Relational databases, XML, in-memory data structures, objects, etc.
Session 02 Module 3: Statements and Operators Module 4: Programming constructs Module 5: Arrays.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
Lecture 11: Generics. The Generic List loading data from a file using System.IO; : namespace EmpListDemo { static class Program { static void Main(string[]
CSCI 3328 Object Oriented Programming in C# Chapter 11: Files and Streams 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX 78539
CSCI 3328 Object Oriented Programming in C# Chapter 6: Methods – Exercises 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX 78539
CSCI 3328 Object Oriented Programming in C# Chapter 4: C# Control Statement – Part I – Exercises 1 Xiang Lian The University of Texas Rio Grande Valley.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
Chapter 11.  Large amounts of data are often stored in a database—an organized collection of data.  A database management system (DBMS) provides mechanisms.
CSCI/CMPE 4341 Topic: Programming in Python Chapter 7: Introduction to Object- Oriented Programming in Python – Exercises Xiang Lian The University of.
Lecture 10 Collections Richard Gesick.
Introduction to LINQ and Generic Collections
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
CSCI 3328 Object Oriented Programming in C# Review: Final Exam
MIS Professor Sandvig MIS 324 Professor Sandvig
The University of Texas – Pan American
CSCI 3328 Object Oriented Programming in C# Chapter 7: Arrays
The University of Texas Rio Grande Valley
The University of Texas – Pan American
The University of Texas – Pan American
Introduction to LINQ Chapter 11 10/28/2015 Lect 4 CT1411.
The University of Texas – Pan American
Introduction to LINQ Chapter 11.
CSCI 3327 Visual Basic Review: Final Exam
CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections UTPA – Fall 2012 This set of slides is revised from lecture slides.
Object Oriented Programming in java
CSCI 3328 Object Oriented Programming in C# Review: Exam II
CSCI 3328 Object Oriented Programming in C# Review: Final Exam
The University of Texas – Pan American
CSCI 3328 Object Oriented Programming in C# Review: Exam II
CSCI 3328 Object Oriented Programming in C# Review: Final Exam
MIS Professor Sandvig MIS 324 Professor Sandvig
CSCI 3328 Object Oriented Programming in C# Review: Final Exam
CSCI 3328 Object Oriented Programming in C# Chapter 11: Files and Streams UTPA – Fall 2012 This set of slides is revised from lecture slides of Prof.
Fundaments of Game Design
CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections – Exercises UTPA – Fall 2012 This set of slides is revised from lecture.
CSCI 3328 Object Oriented Programming in C# Review: Exam II
Presentation transcript:

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

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

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:"); Method declaration public static void Display(IEnumerable results, string header) { Console.Write("{0}", header); foreach (var element in results) Console.Write(" {0}", element); } 8

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

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

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

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.Collections.Generic –List numbers = new List (); –numbers.Add(3); 12

Example of List Coding string[] grades = txtEnterGrade.Text.Split(' '); List scores = new List (); int numScores = grades.Length; foreach (string grade in grades) { scores.Add(Convert.ToInt32(grade)); ListBoxGrades.Items.Add(grade); } 13

Example of List Coding (cont'd) public double summation(List scores, int numScores) //declaration { int sum=0; foreach (int score in scores) { sum = sum + score; } return sum; } 14

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 15

Stack Operation (built-in) Stack students = new Stack (); students.Push("Abbit"); students.Push("Aguero"); students.Push("Castro"); students.Push("Chen"); students.Push("Cruz"); while (students.Count > 0) MessageBox.Show("Popped: " + students.Pop()); 16

Struct – Example public struct Info { public string fName; public string lName; public string Address1; public string Address2; public int zip; public string Tele; } 17

List of Struct public List friendsList = new List (); 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

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

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

Select Those with GPA >+ var foundGPA = from person in friendsList where person.GPA>=Convert.ToSingle(txtSearchGPA.Text) select person; 21

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

More About File Input/Output … 23

Obtaining File Name From Chooser OpenFileDialog fDialog = new OpenFileDialog(); if (fDialog.ShowDialog() == DialogResult.OK) { fileName = (fDialog.FileName.ToString()); MessageBox.Show(fileName); } 24

Reading From a File TextReader 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

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

Example of Employees public class Employee { public string FirstName; public string LastName; public decimal monthlySalaryValue; } 27

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