56
Advanced Language Concepts in C# David Figge [email protected] Session 1 Last Update: 3/09 Page 1 Copyright (C) 2009 by David Figge. All Rights Reserved.

Advanced Language Concepts in C# David Figge [email protected] Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

  • View
    221

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Advanced Language Concepts in C#

David [email protected]

Session 1

Last Update: 3/09 Page 1

Page 2: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Advanced Language Concepts in C#

Welcome

Last Update: 3/09 Page 2

Page 3: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Advanced Language Concepts in C

This is the 3rd in a 3 part series designed to introduce you to C# programming Class 1 introduced you to the basic C#

programming constructs and syntax In Class 2 you delved into Windows and

Web apps In Class 3 we finish up the basic

language elements, then discuss how to take what you have and turn it into a shippable product.

Last Update: 3/09 Page 3

Page 4: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Class Format

Class is designed around the lecture/lab format We will discuss a subject in class in detail, Then YOU will experience that subject with one

or more labs Feel free to ask questions any time

Even stupid ones, like “Why is it called C#?” It’s critical that you understand as we encounter the

material, because we build on this knowledge If it’s appropriate to defer the question until later, I

will Questions between sessions?

Contact me at [email protected] I’ll try to get back to you in a timely manner

Last Update: 3/09 Page 4

Page 5: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Slides

Over the years, I’ve found that the best system for me is to have a series of PowerPoint slides “lead” our discussion This allows me to present the material in an

organized way I also make these slides available to you

This way, you can use them for notes or for a reference in the future

Because they're used as a reference, I try to make sure they're complete This may make them 'busier' than many slide

presentations, but I think it's worth it

I also like to make use of these “speech bubbles”. They help me make a point without losing the focus of the slide.

Don’t let these throw you off.So when you use the slides, remember to ‘run’ the presentation (“View Slide Show”) in order to make the bubbles

move out of the way until appropriate.

Last Update: 3/09 Page 5

Page 6: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Facility Basics

Restrooms, etc. I usually try to take a 15 minute

break every hour or so If you feel I've gone "too long", let me

know.

Last Update: 3/09 Page 6

Page 7: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Environment Basics

You should assume that all data will be wiped off

the disk between sessions

It may not be, but don’t take changes

You can copy it to a USB drive or email to

yourself

Or you can save it to the network

Last Update: 3/09 Page 7

Page 8: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

People Basics

Mostly for my benefit Let’s introduce ourselves with

Your name What you do Why you are taking this course Are there any specific things you were hoping to

learn Your favorite non-computer pass time

Last Update: 3/09 Page 8

Page 9: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Questions

Questions before we go forth?

Last Update: 3/09 Page 9

Page 10: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Advanced Language Concepts in C#

A Quick Review

Last Update: 3/09 Page 10

Page 11: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Class 1: Introduction to C#

Basic language constructs in C# Types, Variables, Loops, Statements, Classes, etc.

Basic Programming Structure Working with Arrays Introduction to Windows applications, including

Event-driven programming Windows forms Common user controls

TextBox, ListBox, RadioButton, etc. Introduction to ADO.NET

DataSets, DataTables Retrieving data from a Database Displaying SQL data in a DataGrid

Introduction to the .Net Framework e.g. Collections

Last Update: 3/09 Page 11

Page 12: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Class 2: Intermediate Windows/Web Apps

Language elements and concepts Working with Classes, Objects, Types Inheritance, Interfaces, Generics, Polymorphism Events, Delegates Working with flat files

ADO Using SQL Commands and Statements Working with DataSets Connected and Disconnected Layers

Web apps Web Forms, Common Web user controls

TextBox, ListBox, etc.

Last Update: 3/09 Page 12

Page 13: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Name: ___________________Pop Quiz!

Copyright (C) 2009 by David Figge. All Rights Reserved.

Question 1 of 4

How is Event Driven Programming different from Procedural Programming? In Procedural Programming, the

program controls the flow, and the program is always in control

In Event Driven programming, Windows remains in control and allows the user to control the flow. The program simply responds to events (either user-initiated or system-initiated).

Last Update: 3/09 Page 13

Page 14: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Name: ___________________Pop Quiz!

Copyright (C) 2009 by David Figge. All Rights Reserved.

Question 2 of 4

What is Polymorphism? Give an example… Polymorphism is a core principle of

OOP, and dictates that an element can be viewed in multiple ways.

An example would be how a FileNotFound exception can also be seen as a System.Exception type

Another example is where a derived class can take inherited elements and override them with new functionality

Last Update: 3/09 Page 14

Page 15: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Name: ___________________Pop Quiz!

Copyright (C) 2009 by David Figge. All Rights Reserved.

Question 3 of 4

What is an Interface? How is it useful? An Interface defines a set of behaviors

(via function definitions), and any class that implements that interface is required to support those behaviors

It’s useful because I can know that all elements that support my interface have a set of functions that will be there

For example, an IWindowElement interface would allow me to know that all elements on a window support drag, drop, select, cut, paste, and copy.

Last Update: 3/09 Page 15

Page 16: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Name: ___________________Pop Quiz!

Copyright (C) 2009 by David Figge. All Rights Reserved.

Question 4 of 4

What is ADO? What can it do for me? ADO (ActiveX Data Objects) is a

core .Net Framework element that provides a common interface to work with data (typically databases)

Many options are supported, and allow for a consistent access to data without concern for the backend data storage.

Last Update: 3/09 Page 16

Page 17: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Class 3: Course Objectives

Understand of the Philosophy of the C# Language

Utilize Structured Methodology in Constructing C# Modules

Create, Compile, Debug C# Programs using

Variables, functions, arrays, classes, .Net framework elements

Understand Language Integrated Query (LINQ)

Understand Security, Class Libraries, and Multi-Threading in C#

Understand the "behind the scenes" elements of namespaces,

assemblies, versioning, attributes, Global Assembly Cache

Understand how to integrate help into your app

Understand what Localization is and how to achieve it

Understand one or more methods for deploying your application

Last Update: 3/09 Page 17

Page 18: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Session 1: Review, Introductions Language INtegrated Query

(LINQ) Session 2:

More Linq (continued) Session 3:

Still More Linq (continued) Session 4:

Creating tables in a Database Attributes

Session 5: Relationships and Referential

Integrity Session 6:

Displaying XML data with DataGrid

Nullable Types SQL Security Concepts .Net Security

Session 7: Class Libraries Namespaces and Assemblies Versioning Global Assembly Cache (GAC) Extern Aliases

Session 8: Multi-Threading

Session 9: Anonymous Methods Integrating Help Localization Windows Setup/Click-Once

Deployment Session 10:

Final Project

Class 3 Schedule

Last Update: 3/09 Page 18

Page 19: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Text is Pro C# 2010and the .Net 4.0Platform

Andrew Troelsen I chose this because:

Good text Reasonable to read Great reference book to

have in the future My exercises are typically not

directly from the book This way you can have more exercises available to you Use it as a source to augment my lectures

Most of our discussions will be chapters 13+ If you can’t find associated reading, let me know

Course Textbook

Questions before we get started?

Last Update: 3/09 Page 19

Page 20: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Review and Starting Project

In The Beginning…

Last Update: 3/09 Page 20

Page 21: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Starting Project

We need a base project on which to build and experiment Further, it can act as a good “review”

We’re going to build an Address program It will contain names, addresses, phone

numbers, and emails We’ll create a simple form to display

these entries Make sense? Ready to begin?

Last Update: 3/09 Page 21

Page 22: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Creating our Starting Application Form

Create a new WPFproject called Addresses

Everyone remember howto do that?

Add 5 labels, 5 TextBoxes,and 4 Buttons as shown.Set these properties:

Labels: Set the text as shown TextBoxes:

Names: tbName, tbAddress, tbCSZ, tbPhone, tbEmail No Initial Text

Buttons: Names: btnStart, btnPrevious, btnNext, btnEnd Text: “|<<“, “<<“, “>>”, “>>|”

No events yet.Last Update: 3/09 Page 22

Page 23: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Keeping Addresses

Create a new class Entry. In it have: Fields and (public) Default Properties for

Name, Address, CSZ, Phone and Email (all strings)

Example: public string Name { get; set; } A default constructor (does nothing) A constructor that takes 5 arguments,

and uses those to initialize the fields.

Anyone know or remember how we use Default Properties in C#?

Last Update: 3/09 Page 23

What’s a Default Constructor, and why would we want one that does

nothing?

The default constructor is one that the constructor no parameters. It can be handy for creating empty objects.

Usually, the constructor sets member fields to their ‘empty’ values. In this case, that would be empty strings (which already happens), so ‘do nothing’ is appropriate.

Page 24: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Creating a Collection Class Sometimes its convenient to have a collection class

A class who’s job is to maintain a collection of another type This could be handy for our Entry class We could, of course, create a collection variable (e.g.

List<Entry> addressList) But then we don’t have access to things like constructors

To create a Collection Class, we’ll simply derive from the List class like this

public class Entries : List<Entry> { … } We could put this in a separate file, but for organizational

reasons, I’m putting mine in Entry… Now let’s move on to a constructor

This will create 10 default names – just to get us up and running…

Last Update: 3/09 Page 24

Page 25: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Code

Example Entries Constructor

public Entries(){ string[] names = {"Bob Anderson", "Bill Henderson", "Charlie Jones",

"David King", "Bob Lincoln", "Sam Peterson", "David Roberts", "John Smith","Steve Thompson", "Bill Williams" };

string[] addresses = {"101 Main St", "528 W 32nd", "2938 N 39th St","2349 E 83rd St", "200 Belmont Pl", "39434 W Smithson Rd","861 Jones Way NE","9483 349th St W", "333 33rd W", "1601 Pennsylvania Ave"};

string[] cszs = {"Belmont, NC 93849", "San Francisco, CA 28348","New York, NY 39483", "Seattle, WA 93849", "Bothell, WA 93833","Kirkland, WA 93322", "Fargo, ND 33293", "New Orleans, LA 22393","Miami, FL 11928", "Providence, RI 29384" };

string[] phones = {"234-304-3290", "403-203-2956", "550-203-3948","222-309-3093", "854-394-2293", "276-376-2273", "210-204-3948","345-339-3904", "206-394-4488", "425-394-3933" };

string[] emails = { "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]","[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]" };

for (int x = 0; x < 10; x++) { Entry e = new Entry(names[x], addresses[x], cszs[x], phones[x], emails[x]); Add(e); }}

Last Update: 3/09 Page 25

Any questions on what this is doing?

When everyone’s ready, we’ll continue…

Page 26: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Creating an AddressList

Back in our Form CS file. create two new class variables: Entries AddressList = new Entries();

This calls the constructor and creates the 10 entries

int current = 0; This keeps track of which entry we’re

displaying

Last Update: 3/09 Page 26

Page 27: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

We’re Getting Closer…

Next we’re going to create a Display function Its job will be to take an Entry and display

it on the form Here’s the code (still in the Form CS

file)…

Last Update: 3/09 Page 27

Page 28: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Code

Example The Display Function

// Call Display from the form’s constructor to show #1

void Display(){ Entry e = AddressList[current]; tbName.Text = e.Name; tbAddress.Text = e.Address; tbCSZ.Text = e.CSZ; tbPhone.Text = e.Phone; tbEmail.Text = e.Email;}

At this point you should compile and run.

Last Update: 3/09 Page 28

Page 29: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

“Getting Back Into It” Exercise

The last step is to get the buttons working

Add button event handlers for the following: |<< -- Moves current to the first entry (0) << -- Moves to the previous entry (if any) >> -- Moves to the next entry (if any) >>| -- Moves to the last entry

(Entries.Count-1) Good Luck!

20 MinutesLast Update: 3/09 Page 29

Page 30: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Code

Example My Solution

private void btnStart_Click(object sender, EventArgs e){ current = 0; Display();}private void btnEnd_Click(object sender, EventArgs e){ current = AddressList.Count - 1; Display();}private void btnPrevious_Click(object sender, EventArgs e){ if (current > 0) { current--; Display(); }}private void btnNext_Click(object sender, EventArgs e){ if (current < AddressList.Count - 1) { current++; Display(); }}

Last Update: 3/09 Page 30

Everybody got it working?

Page 31: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Advanced Data Access

Language Integrated Query (LINQ)

Last Update: 3/09 Page 31

Page 32: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Language Integrated Query

Linq is a relatively new feature of C# It attempts to create a query construct

within the C# language to allow SQL-like queries to be executed on just about any collection From databases to lists to arrays

The easiest way to see this is to do this Start a new Console application called

LinqTest We’ll come back to the Addresses soon enough

Here’s the code for the Main function Type it in, then we’ll discuss it…

Last Update: 3/09 Page 32

Page 33: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Code

Example LinqTest.cs

static void Main(string[] args){ string[] Cars = { "Porsche", "Saab", "Ferrari",

"Mercedes", "Volvo", "Mustang", "Chevy" };

IEnumerable<String> names = from c in Cars where c.Length > 5 select c;

foreach (string s in names) Console.WriteLine(s);}

Last Update: 3/09 Page 33Type it in, then we’ll look at it…

So we start off with a collection of strings (in this case, cars)

The next line is, obviously, the Linq line. Linq uses several keywords…

Similar to foreach(string c in Cars), we have from c in Cars.

The “from” variable (c) is the one that will take on the value of each item in

Cars (one at a time) so we can examine the contents.

Cars is, of course, the collection that we are querying.

The select clause is the one that actually adds an element to the

results.

Those 3 elements are required in all Linq statements: the from, in, and

select clauses.

Most Linq statement also include a where clause. This reduces the result set to only those matching the clause (in this case, c.Length > 5). Note that we use the c variable here, because

during the execution of the statement, it holds the current

element being examined.

Making sense so far?

A linq statement returns an IEnumerable object, in this case based

on strings (since we were using strings). Among other things,

IEnumerable works well with foreach.

So here we use the foreach statement to display the result collection from the Linq query.

Does this make sense to everyone?

For those who know SQL, this is similar to the SQL statement (if a database had

strings like Cars)

select * from Cars where Cars.Length > 5

Note: Text in gray indicates you don’t need to type this (Visual Studio

added this for you)

Page 34: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Code

Example Linq Example: Even Digits

static void Main(string[] args){ int[] digits = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

IEnumerable<int> evens = from i in digits where i % 2 == 0 select i;

foreach (int i in evens) Console.Write("{0} ",i.ToString());

Console.WriteLine();}

Last Update: 3/09 Page 34

Okay. Let’s put together another example. We’ll start with a collection

of digits…

Our goal is to identify and print all the even digits. How does our linq

statement start?

Because we’re collecting integers, we’ll store the results in an IEnumerable<int>

data type (called evens)

What does our Linq statement look like? Some questions to consider:

How do we put together the keywords? The keywords are:select, in, where and from (not necessarily in that order )

How to you determine that a number is even?

Anyone want to give it a try?

So this line selects all even numbers.

How can we display them?

This displays the numbers (separated by a space), then moves to the next

line after all have been printed.Type it in. See

if it works…Questions So

Far?

Page 35: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Name: ___________________Pop Quiz!

Copyright (C) 2009 by David Figge. All Rights Reserved.

Question 1 of 2

What keywords are used with Linq?How would I put together a statement to select all passing students (Grade != FAIL)? from, in, select, where (optional) from s in Students

where s.Grade != FAILselect s

Last Update: 3/09 Page 35

Page 36: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Name: ___________________Pop Quiz!

Copyright (C) 2009 by David Figge. All Rights Reserved.

Question 2 of 2

What datatype is returned from a Linq query? Results are of type IEnumerable<T>

Last Update: 3/09 Page 36

Page 37: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Implicitly Typed Variables

C# supports a variable data type using the keyword var, for example:

So, in this case, result takes on the data type based on what GetData returns

There are some great uses for this, but one really convenient one is Linq!

Here's the Even Number code using var:Last Update: 3/09 Page 37

var result = GetData(); // var set based on return type

Page 38: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Code

Example Even Digits with var

static void Main(string[] args){ int[] digits = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

var evens = // Was Ienumerable<int> evens = from i in digits where i % 2 == 0 select i;

foreach (int i in evens) Console.Write("{0} ",i.ToString());

Console.WriteLine();}

Last Update: 3/09 Page 38

As you can see, this makes the line much more readable. And since the compiler knows the data type, why

not have it be automatic?

Although var has a convenience element, there are also times when you simply have

to use var (because the data type is not defined). We’ll see that in a few minutes…

Page 39: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Using Linq with Classes

Since a class is really just a user-defined data type, you can also use Linq with classes You can either put the results into an

IEnumerable<ClassType> type, or a var Let’s put some temporary code into our

Address program to look up John Smith’s phone number from the constructor and show it in a MessageBox. How would we do this?

Here’s my solution:

Last Update: 3/09 Page 39

Page 40: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Code

Example Looking Up a Phone Number

public AddressFrm(){ InitializeComponent(); Display(); var fnd = from e in AddressList where e.Name == "John Smith“ select e; Entry[] ents = fnd.ToArray<Entry>(); MessageBox.Show("John Smith's Phone Number is " + ents[0].Phone);}

Last Update: 3/09 Page 40

First we select the record for John Smith. Does this code make sense?

Now we display it. The MessageBox.Show displays the

message box.

Here we take the results (fnd) and convert it into an Entry array. This will make it easier to work with in our program. We use the ToArray function for this.

Anyone have questions on any of this that we’ve covered?

Since it was just temporary code, comment out this code now so it doesn’t interfere with the program’s operation.

Page 41: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Adding Find to Addresses

Last Update: 3/09

Add logic to your Addresses program to implement a Find Record(s) feature

I suggest putting a “Search For” TextBox on your form with a Find button. When Find is hit, any name matching the search text is selected.

Use Linq to select the Entries matching the search string You can use the string’s .Contains() function to do this

You’ll need to Allow for multiple records selected

What if I search for all entries with “Bob”? Restrict the buttons to work only on selected entries

Create a new Entry[] SelectedEntries variable. Deal with results that have no records found

Allow a way to ‘un-find’ to go back to all entries Perhaps a button that cancels the Find, or Find with a blank name box Use a SelectAllEntries function to reset to full list (we’ll use this later)

Good luck!

Page 41

60 Minutes

Page 42: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

My Solution

My solution can be made available to anyone who was unable to complete the exercise

I went through these steps: Created Entry[] SelectedEntries to keep track of

current selection I default it at the beginning to all (AddressList)

Changed Display and buttons handlers to use SelectedEntries

I added the controls on the form and tied them in via the button event handler

Empty box = select all again (selectedEntries=AddressList)

Used Linq to select names containing find text If no entries, printed error and returned Otherwise, set SelectedEntries to new list via ToArray().

Last Update: 3/09 Page 42

Page 43: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Advanced Data Access

Advanced LINQ Constructs

Last Update: 3/09 Page 43

Page 44: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Advanced Linq Constructs

Linq has a few more advanced features worth looking at (which we will over the next several slides). These are Use of Anonymous Types for results Deferred vs Immediate Execution Advanced Operators

Join, On Equals, Into, Orderby, Group By Using Linq with other data collections

Databases, XML, etc.

Last Update: 3/09 Page 44

Page 45: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Anonymous Result Types

There can be disadvantages to retrieving entire classes of data using Linq When data is remote and classes are large,

you might pass lots of unnecessary data over a network connection

Anonymous Types can help An anonymous type is just that: a type

(class) that is created temporarily and without a name

In this case, it can be used by Linq to store the results of a query

Let’s look at an example…

Last Update: 3/09 Page 45

Page 46: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Code

Example An Anonymous Class Example

... var dispdata = from ba in BankAccounts select new { ba.Name, ba.Balance };

foreach(var i in dispdata) Console.WriteLine("{0} has a balance of {1}", i.Name, i.Balance);

Last Update: 3/09 Page 46

So we start off looking pretty normal. Select all records from the BankAccounts collection.

However, instead of grabbing the entire record (perhaps hundreds of fields), we grab only two.

This is the Anonymous Type syntax. It says, “create a new type” containing just these elements.

Note that we have to use the variable type identifier var, since the return type doesn’t

really even have a name.

Here’s our foreach loop. Again, we have to use the var keywords for the type, since it doesn’t really have a name.

When accessing i, we can use the Name and Balance properties (defaulted from the BankAccount type).

Cust=ba.Name, Bal=ba.Balance };

Note that you can also name the elements as you select them using this syntax. That would also imply changes to

the display line (to reference Cust and Bal)…

Like this.

i.Cust, i.Bal);

Does this make sense. Any questions on this?Watch me as a rewrite our original “phone number message box in the constructor” to use anonymous types

(you don’t need to do this, just watch…)

Page 47: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Code

Example MessageBox Example

public AddressFrm(){ InitializeComponent(); SelectAllEntries(); // Select all entries to start Display(); var fnd = from e in AddressList where e.Name == "John Smith" select new { FullName = e.Name, PhoneNum = e.Phone }; foreach(var v in fnd) MessageBox.Show(v.FullName + "'s Phone Number is " + v.PhoneNum);}

Last Update: 3/09 Page 47

Questions onthis?

Again, the benefit of all this is a) less data must cross the wire (in the case of remote data), and b) it de-couples you

from the original data (it would be easy to change this code to adapt to the changes in the Entry class).

Page 48: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Deferred Execution

It’s important to note that Linq uses Deferred Execution This means that the query isn’t actually

executed until you request the results For example, within the foreach loop

This has a couple of benefits If the underlying data changes, your

loop uses it You don't search through data that you

don't need Let's look at this in action…

Last Update: 3/09 Page 48

Page 49: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Code

Example Deferred Execution

static void Main(string[] args){ int[] numbers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

var evens=from i in numbers where i % 2 == 0 select i;

foreach (int i in evens) // Produces 0 2 4 6 8 Console.Write("{0} ", i.ToString()); Console.WriteLine();

numbers[5] = 10;

foreach (int i in evens) // Produces 0 2 4 10 6 8 Console.Write("{0} ", i.ToString()); Console.WriteLine();}

Last Update: 3/09 Page 49

This code should loop pretty familiar. We go through numbers and print the even ones, based

on the linq statement above.

But here we change things up a bit. We change the element that had 5 in it to be 10 (an even number).

Now, without executing the Linq statement again, we do another

foreach loop. This time it shows the element with 10.

What this shows us is that the linq statement is saved, then executed each time (in this case) the foreach loop requests it. That’s what’s meant by

deferred execution.

This ‘connection’ is broken when the evens variable goes out of scope.

So one way you can force this ‘disconnect’ is to this is to copy the result set into (for example) an

array. If you aren’t using evens, it won’t be executing its associated linq statement.

Deferred Executionmake sense?

Page 50: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Advanced Linq Operators

As you may be able to see, Linq is patterned after the SQL language Many of the keywords match SQL Phrasing is similar to SQL The difference is that Linq was designed to

work with internal data structures as well as external data (like databases)

So let’s take a look at some of the more advanced keywords of Linq Remember, although these were patterned

after and designed to work with SQL, you do not need a database to make these work!

Last Update: 3/09 Page 50

Page 51: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Linq Query Operators

Last Update: 3/09 Page 51

Query Operators Meaning

from, in Used to define the base Linq expression to extract a subset of data from a container

where Used to specify a restriction to retrieved data

select Used to select a specific element from the container

join, on, equals, into Performs joins based on a specific key element

orderby, ascending, descending

Allows the resulting subset to be ordered ascending or descending

group, by Yields a subset that is grouped by a specified value

Let’s modify our Addressesprogram to order by name…

Page 52: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Code

Example Using Orderby

...// This function allows easy setting to "all" entriesvoid SelectAllEntries(){ //SelectedEntries = AddressList.ToArray(); SelectedEntries = (from s in AddressList orderby s.Name select s).ToArray<Entry>();}

private void btnFind_Click(object sender, EventArgs e){ ... var ents = from c in AddressList where c.Name.Contains(tbFind.Text) orderby c.Name select c;

Entry[] found = ents.ToArray<Entry>(); ...}

Last Update: 3/09 Page 52

We’ll see how some of theother keywords fit in later…

Page 53: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Name: ___________________Pop Quiz!

Copyright (C) 2009 by David Figge. All Rights Reserved.

Question 1 of 1

How would I put together a Linq query to find all students that passed (Grade >= ‘C’) in order of grade, then name?

You may have to use an educated guess on some of this…

from s in Studentswhere s.Grade >= ‘C’orderby s.Grade,s.Nameselect s;

Last Update: 3/09 Page 53

Page 54: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Address List Categories

Last Update: 3/09

Time to play a biton your own

We’re going to adda Category optionto our Addresses program (so it looks like this) This will allow the user to narrow the

selection based on contact type to Friend, Business, or All

Following me so far? Ready for the steps?

Page 54

Page 55: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Address List Categories Steps

Last Update: 3/09

1. Add the controls to the form Three RadioButtons: All, Friends, Business

I chose to group those in a Group Box A new label/textbox to display Friend/Business

within the record data

2. Add ContactType to Entry class and initialize it Create an enum for the different types (I used CTypes) Initialize it like we’ve done for the other fields

3. Modify Display to display Friend/Business Fill in that new textbox with either “Friend” or “Business”

4. Add logic to SelectAllEntries() to select category So SelectAllEntries will select all entries in the category I added a new class field “currentCategory”

5. Add logic to Find to use the current category You can use SelectAllEntries, then find within that list

6. Add logic to reselect on RadioButton This should reset your selection (this can reset Find text to ‘none’)

7. There’s a lot to this, but you’re in level 3 now – you can handle it!Page 55

60 Minutes

Page 56: Advanced Language Concepts in C# David Figge dfigge@uw.edu Session 1 Last Update: 3/09Page 1Copyright (C) 2009 by David Figge. All Rights Reserved

Copyright (C) 2009 by David Figge. All Rights Reserved.

Advanced Language Concepts in C#

End of Session 1

Last Update: 3/09 Page 56