close

Se connecter

Se connecter avec OpenID

Advanced Language Concepts in C#

IntégréTéléchargement
Advanced Language Concepts in C#
Session 1
Last Update: 3/09
David Figge
dfigge@uw.edu
Page 1
Copyright (C) 2009 by David Figge. All Rights Reserved.
Welcome
Advanced Language Concepts in C#
Last Update: 3/09
Page 2
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
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 dfigge@uw.edu
I’ll try to get back to you in a timely manner
Last Update: 3/09
Page 4
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
I also like to make use of these “speech
PowerPoint slides
“lead”
our
discussion
bubbles”.
They help
me make
a point


Show”) in order to make the bubbles
move out of the way until appropriate.
I also make these slides available to you


without
losing the
focusmaterial
of the slide. in an
This allows me
to
present
the
So when
you
use the slides,
remember
Don’t let these throw you off.
to
‘run’
the
presentation (“View Slide
organized way
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
Last Update: 3/09
Page 5
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
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
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
Copyright (C) 2009 by David Figge. All Rights Reserved.
Questions
Questions before we go forth?
Last Update: 3/09
Page 9
Copyright (C) 2009 by David Figge. All Rights Reserved.
A Quick Review
Advanced Language Concepts in C#
Last Update: 3/09
Page 10
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


Introduction to ADO.NET




TextBox, ListBox, RadioButton, etc.
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
Copyright (C) 2009 by David Figge. All Rights Reserved.
Class 2: Intermediate Windows/Web Apps

Language elements and concepts






Inheritance, Interfaces, Generics, Polymorphism
Events, Delegates
Working with flat files
Custom controls and User controls
Printing
Web apps

Round-trips, Web Forms, Common Web user controls


.Net Framework




TextBox, ListBox, RadioButton, etc.
XML
Regular Expressions
Debugging and Tracking
Data in Web Apps

Create, Read, Update, Delete (CRUD)
Last Update: 3/09
Page 12
Copyright (C) 2009 by David Figge. All Rights Reserved.
Pop Quiz!
Name: ___________________
Question 1 of 4

How is Event Driven Programming
different from Procedural
Programming?


Last Update: 3/09
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).
Page 13
Copyright (C) 2009 by David Figge. All Rights Reserved.
Pop Quiz!
Name: ___________________
Question 2 of 4

What is Polymorphism? Give an
example…



Last Update: 3/09
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
Page 14
Copyright (C) 2009 by David Figge. All Rights Reserved.
Pop Quiz!
Name: ___________________
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

Last Update: 3/09
For example, an IWindowElement interface
would allow me to know that all elements on
a window support drag, drop, select, cut,
paste, and copy.
Page 15
Copyright (C) 2009 by David Figge. All Rights Reserved.
Pop Quiz!
Name: ___________________
Question 4 of 4

What is ADO? What can it do for me?


Last Update: 3/09
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.
Page 16
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
Copyright (C) 2009 by David Figge. All Rights Reserved.
Class 3 Schedule






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
Last Update: 3/09




Page 18
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
Copyright (C) 2009 by David Figge. All Rights Reserved.
Course Textbook

Text is Pro C# 2008
and the .Net 3.5
Platform


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


Andrew Troelsen
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 14+
Questions
before we
If you can’t find associated reading, let me
know
Last Update: 3/09
get started?
Page 19
Copyright (C) 2009 by David Figge. All Rights Reserved.
In The Beginning…
Review and Starting Project
Last Update: 3/09
Page 20
Copyright (C) 2009 by David Figge. All Rights Reserved.
Starting Project

We need a base project on which to
build and experiment


We’re going to build an Address
program



Further, it can act as a good “review”
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
Copyright (C) 2009 by David Figge. All Rights Reserved.
Creating our Starting Application Form

Create a new Windows Forms
project called Addresses


Everyone remember how
to do that?
Add 5 labels, 5 TextBoxes,
and 4 Buttons as shown.
Set these properties:


Labels: Set the text as shown
TextBoxes:



Buttons:



Names: tbName, tbAddress, tbCSZ, tbPhone, tbEmail
No Initial Text
Names: btnStart, btnPrevious, btnNext, btnEnd
Text: “|<<“, “<<“, “>>”, “>>|”
No events yet.
Last Update: 3/09
Page 22
Copyright (C) 2009 by David Figge. All Rights Reserved.
Keeping Addresses
Anyone know or remember how we
use Default Properties in C#?

Create a new class Entry. In it have:

Fields and (public) Default Properties for
Name, Address, CSZ,What’s
Phone
and
Email
a Default
Constructor,
and(all
why would we want one that does
strings)
nothing?



Example: public string Name { get; set; }
A default constructor (does nothing)
A constructor that takes 5 arguments, and
The default constructor is one that the constructor no
uses those to
initialize
the
fields.
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.
Last Update: 3/09
Page 23
Copyright (C) 2009 by David Figge. All Rights Reserved.
Creating a Collection Class

Sometimes its convenient to have a collection class



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



A class who’s job is to maintain a collection of another
type
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
Copyright (C) 2009 by David Figge. All Rights Reserved.
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 = {
"bob@anderson.com", "bill@henderson.com", "charlie@jones.com",
"david@king.com", "bob@lincoln.com","sam@peterson.com", "david@roberts.com",
"john@smith.com", "steve@thompson.com", "bill@williams.com" };
for (int x = 0; x < 10; x++)
{
Entry e = new Entry(names[x], addresses[x], cszs[x], phones[x], emails[x]);
Add(e);
}
}
When
Any questions
everyone’s
onready,
what
we’ll
this continue…
is doing?
Last Update: 3/09
Page 25
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;

Last Update: 3/09
This keeps track of which entry we’re displaying
Page 26
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
Copyright (C) 2009 by David Figge. All Rights Reserved.
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
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 Minutes
Last Update: 3/09
Page 29
Copyright (C) 2009 by David Figge. All Rights Reserved.
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?
Copyright (C) 2009 by David Figge. All Rights Reserved.
Language Integrated Query (LINQ)
Advanced Data Access
Last Update: 3/09
Page 31
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



The easiest way to see this is to do this
Start a new Console application called
LinqTest


From databases to lists to arrays
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
Copyright (C) 2009 by David Figge. All Rights Reserved.
LinqTest.cs
Note: Text in gray
A linq statement returns
Soan
we start off with
a collection
of need
indicates
you don’t
IEnumerable object, in this case based
strings (in this
cars)(Visual Studio
to case,
type this
static voidonMain(string[]
args)
strings (since we were using
added this for you)
{
strings). Among other things,
Similar to foreach(string c in
IEnumerable
well with foreach.
string[]
Carsfrom
= works
{c in"Porsche",
"Saab", "Ferrari",
Cars), we have
Cars.
"Mercedes", "Volvo", "Mustang", "Chevy" };
The next line is, obviously, the Linq
Most
Linq
statement
alsokeywords…
include a
line.
Linq
uses several
IEnumerable<String> names = where clause. This reduces the result
set to only those matching the clause
from c
For
those
who
know
SQL,are
thisrequired
is similarinto
Those
3the
elements
all
Cars is,(in
of
course,
collection
this
case,
c.Length
>
5).
Note
that
in Cars
thewe
SQL
statement
(if athe
database
had
Linq
statements:
from, in,
and
that
are
querying.
we
use
the
c
variable
here,
because
Does this
Making
make
sense
sense
so
tofar?
everyone?
strings
like clauses.
Cars)
where c.Length > 5
select
during the execution of the
select c;
statement, it holds the current
select * from Cars where Cars.Length > 5
element being examined.
The
select
clause
is
the
one
that
The
“from”
variable
(c)
is
the
one
foreach (string actually
s in names)
adds an element to the
that will take on the value of each
Console.WriteLine(s);
So here we use the foreach
item in Cars (one at a time) so we can results.
}
statement to display the result
examine the contents.
collection from the Linq query.
Last Update: 3/09
Page 33
Type it in, then we’ll look at it…
Copyright (C) 2009 by David Figge. All Rights Reserved.
What does our Linq statement look like? Some questions to consider:
Linq Example: Even Digits
How do we put together the keywords? The keywords are:
select,
in, where
and from (not necessarily
in that order )
static
void
Main(string[]
args)
Because
we’re collecting integers,
we’ll
store
thetoresults
in an IEnumerable<int>
{
How
you determine
that a number is even?
data
type
(called
evens)
int[] digits = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Anyone want to give it a try?
IEnumerable<int> evens =
from i in digits where i % 2 == 0 select i;
foreach (int
evens)
So this ilinein
selects
all even numbers.
Console.Write("{0} ",i.ToString());
How can we display them?
Console.WriteLine();
}
This displays the numbers (separated
Our goal is to identify and print all
by a space), then moves
toLet’s
the next
put
together
another
theOkay.
even digits.
How
does our
linq
line after all haveexample.
been printed.
We’ll start
with a collection
statement
start?
Questions
it in. See
So
of digits…Type
if it Far?
works…
Last Update: 3/09
Page 34
Copyright (C) 2009 by David Figge. All Rights Reserved.
Pop Quiz!
Name: ___________________
Question 1 of 2

What keywords are used with Linq?
How would I put together a
statement to select all passing
students (Grade != FAIL)?


Last Update: 3/09
from, in, select, where (optional)
from s in Students
where s.Grade != FAIL
select s
Page 35
Copyright (C) 2009 by David Figge. All Rights Reserved.
Pop Quiz!
Name: ___________________
Question 2 of 2

What datatype is returned from a
Linq query?

Last Update: 3/09
Results are of type IEnumerable<T>
Page 36
Copyright (C) 2009 by David Figge. All Rights Reserved.
Implicitly Typed Variables

C# supports a variable data type using
the keyword var, for example:
var result = GetData(); // var set based on return type



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
Copyright (C) 2009 by David Figge. All Rights Reserved.
Even Digits with var
As you can see, this
makes the line
static void Main(string[]
args)
much more readable. And since the
{
compiler knows the data type, why
int[] digits = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
not have it be automatic?
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
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 38
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


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.


You can either put the results into an
IEnumerable<ClassType> type, or a var
How would we do this?
Here’s my solution:
Last Update: 3/09
Page 39
Copyright (C) 2009 by David Figge. All Rights Reserved.
Looking Up a Phone Number
public AddressFrm()
{
First we select the record for John
InitializeComponent();
Smith. Does this code make sense?
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);
Here
we take the results (fnd) and convert it into an
}
it
was
Entry array. This will make it easier Anyone
to Since
work have
with
injust
questions
on any
of this
Now
wetemporary
display
it. code,
The
outthis.
this
code
nowdisplays
so it doesn’t
our program. We use the ToArray comment
functionMessageBox.Show
for
that
we’ve
covered?
the
interfere with themessage
program’s
operation.
box.
Last Update: 3/09
Page 40
Copyright (C) 2009 by David Figge. All Rights Reserved.
Adding Find to Addresses

Add logic to your Addresses program to implement a Find
Record(s) feature


Use Linq to select the Entries matching the search string


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.
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



Deal with results that have no records found
Allow a way to ‘un-find’ to go back to all entries



Create a new Entry[] SelectedEntries variable.
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!
60 Minutes
Last Update: 3/09
Page 41
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




Last Update: 3/09
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().
Page 42
Copyright (C) 2009 by David Figge. All Rights Reserved.
Advanced LINQ Constructs
Advanced Data Access
Last Update: 3/09
Page 43
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

Last Update: 3/09
Databases, XML, etc.
Page 44
Copyright (C) 2009 by David Figge. All Rights Reserved.
Anonymous Result Types

There can be disadvantages to retrieving
entire classes of data using Linq


Anonymous Types can help



When data is remote and classes are large,
you might pass lots of unnecessary data over
a network connection
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
Copyright (C) 2009 by David Figge. All Rights Reserved.
An Anonymous Class Example
Note that we have to use the variable type
identifier var, sinceThis
theisreturn
type
the Anonymous
Type syntax. It says, “create
doesn’t really even have
a
name.
a new type” containing just these elements.
...
var dispdata = from ba
in BankAccounts
Bal=ba.Balance
};
select new { Cust=ba.Name,
ba.Name, ba.Balance
};
foreach(var
i inoffdispdata)
So we start
looking pretty normal. Select all
recordsNote
fromthat
the you
BankAccounts
collection.
Console.WriteLine("{0}
balance
of {1}",
canhas
also a
name
the elements
as you select
However,them
instead
of this
grabbing
theThat
entire
record
i.Cust,
i.Bal);
i.Name,
i.Balance);
using
syntax.
would
also imply changes to
(perhaps hundreds
of
fields),
we
grab
only
two.
the display line (to reference Cust and Bal)…
Like this.
Here’s our foreach loop. Again, we have to use the var
keywords for the type, since it doesn’t really have a name.
Watch me
as acan
rewrite
ourName
original
number
When accessing
i, we
use the
and“phone
Balance
Does this
make sense.
Any questions
on this?
message
box in the
constructor”
to use anonymous
types
properties
(defaulted
from
the BankAccount
type).
(you don’t need to do this, just watch…)
Last Update: 3/09
Page 46
Copyright (C) 2009 by David Figge. All Rights Reserved.
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);
}
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).
Last Update: 3/09
Page 47
Questions on
this?
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


This has a couple of benefits



For example, within the foreach loop
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
Copyright (C) 2009 by David Figge. All Rights Reserved.
Deferred Execution
What this shows us is that the linq statement is
saved, then
each time (in args)
this case) the
static
voidexecuted
Main(string[]
foreach loop requests it. That’s what’s meant by
{
deferred execution.
int[] numbers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var evens=from i in numbers where i % 2 == 0 select i;
}
Now, without
foreach (int i in evens) // Produces
0 executing
2 4 6 8the Linq
statement again, we do another
Console.Write("{0} ", i.ToString());
foreach loop. This time it shows the
Console.WriteLine();
This ‘connection’ is broken when the evens
element with 10.
variable goes out of scope.
digits[5] = 10;
This code should loop pretty familiar. We go
So one way you can force
this ‘disconnect’
is to
through
numbers and
print the even ones, based
this is to (int
copy the
set into (for
example)
an
foreach
i result
in evens)
//
0 2above.
4 10 6 8
on
theProduces
linq statement
array. If you aren’t using ",
evens,
it won’t be
Console.Write("{0}
i.ToString());
Butexecuting
here we change
things linq
up astatement.
bit. We change the
its associated
Console.WriteLine();
element that had 5 in it to be 10 (an even number).
Last Update: 3/09
Deferred Execution
make sense?
Page 49
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
Copyright (C) 2009 by David Figge. All Rights Reserved.
Linq Query Operators
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 Addresses
program to order by name…
Last Update: 3/09
Page 51
Copyright (C) 2009 by David Figge. All Rights Reserved.
Using Orderby
...
// This function allows easy setting to "all" entries
void 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 the
other keywords fit in later…
Copyright (C) 2009 by David Figge. All Rights Reserved.
Pop Quiz!
Name: ___________________
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?


Last Update: 3/09
You may have to use an educated guess on
some of this…
from s in Students
where s.Grade >= ‘C’
orderby s.Grade,s.Name
select s;
Page 53
Copyright (C) 2009 by David Figge. All Rights Reserved.
Address List Categories


Time to play a bit
on your own
We’re going to add
a Category option
to 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?
Last Update: 3/09
Page 54
Copyright (C) 2009 by David Figge. All Rights Reserved.
Address List Categories Steps
1.
Add the controls to the form

Three RadioButtons: All, Friends, Business


2.


You can use SelectAllEntries, then find within that list
Add logic to reselect on RadioButton

7.
So SelectAllEntries will select all entries in the category
I added a new class field “currentCategory”
Add logic to Find to use the current category

6.
Fill in that new textbox with either “Friend” or “Business”
Add logic to SelectAllEntries() to select category

5.
Create an enum for the different types (I used CTypes)
Initialize it like we’ve done for the other fields
Modify Display to display Friend/Business

4.
A new label/textbox to display Friend/Business
within the record data
Add ContactType to Entry class and initialize it

3.
I chose to group those in a Group Box
This should reset your selection (this can reset Find text to ‘none’)
There’s a lot to this, but you’re in level 3 now – you can handle it!
60 Minutes
Last Update: 3/09
Page 55
Copyright (C) 2009 by David Figge. All Rights Reserved.
End of Session 1
Advanced Language Concepts in C#
Last Update: 3/09
Page 56
Copyright (C) 2009 by David Figge. All Rights Reserved.
Auteur
Документ
Catégorie
Без категории
Affichages
4
Taille du fichier
3 046 Кб
Étiquettes
1/--Pages
signaler