neal stublen [email protected]. tonight’s agenda arrays and collections dates and times string...

57
C#: INTRODUCTION FOR DEVELOPERS Neal Stublen [email protected]

Upload: maude-french

Post on 29-Dec-2015

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

C#: INTRODUCTION

FOR DEVELOPERS

Neal Stublen

[email protected]

Page 2: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Tonight’s Agenda

Arrays and collections Dates and times String methods Q&A

Page 3: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

BUT FIRST...SOME REVIEW

Page 4: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Practice Exercise

Let’s debug a simple program... Pick a random number Solicit a guess from the user Compare the number and indicate if the

guess was too low or too high and ask for another guess

Quit if the guess is correct, or

we run out of chances

Page 5: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

CHAPTER 8

ARRAYS AND COLLECTIONS

Page 6: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

What is an array?

int

string

decimal

int

string

decimal

int

string

decimal

int

decimal decimal

“Elements” in the array

We can declare variablesfor individual values.

We can also declare an “array”of values.

Page 7: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Declaring an Array

int0

int0

int0

int0

But an array is much easier…

int[] highScores;highScores = new int[5];

We could do…

int highScore1 = 0;int highScore2 = 0;int highScore3 = 0;int highScore4 = 0;int highScore5 = 0;

Tip: Declare and initialize on the same line.

int[] highScores = new int[5];

int0

Track top five high scores in a game…

Page 8: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Initializing an Array

We can initialize elements individually…

int[] highScores = new int[5];

// First element is at index 0 highScores[0] = 5000;highScores[1] = 5000;highScores[2] = 5000;highScores[3] = 5000;highScores[4] = 5000;

Or we can initialize elements during creation of the array…

int[] highScores = new int[5] { 5000, 5000, 5000, 5000, 5000 };

Arrays are automatically initialized to default values, but thosevalues may not suit your purposes.

Page 9: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Using an ArrayWhat if the array size changes?

int[] highScores = new int[20] { 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000 };

Use a loop…

int[] highScores = new int[20];

for (int index = 0; index < 20; ++index ){ highScores[index] = 5000;}

Tip: Define constants instead of using hard-coded values to defineand initialize an array.

const int NUM_HIGH_SCORES = 20;const int MIN_HIGH_SCORE = 5000;

int[] highScores = new int[NUM_HIGH_SCORES];

for (int index = 0; index < highScores.Length; ++index ){ highScores[index] = MIN_HIGH_SCORE;}

How could you improve this further?

Page 10: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Iterating Over an Array

for (int index = 0; index < highScores.Length; ++index){ int score = highScores[index]; file.writeScore(score);}

foreach (int score in highScores){ file.writeScore(score);}

What if we need to access each element in an array?

Page 11: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Rectangular Arrays

int0

int0

int0

int0

int[,] highScores = new int[NUM_DAYS, NUM_HIGH_SCORES];

int0

Track top five high scores in a game for the last three days…

int0

int0

int0

int0

int0int

0int0

int0

int0

int0

for (int day = 0; day < highScores.GetLength(0); ++day){ for (int score = 0; score < highScores.GetLength(1); ++score) { highScores[day, score] = MIN_HIGH_SCORE; }}

Page 12: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

What is a jagged array?

int[][] highScores = new int[12][];highScores[0] = new int[31];highScores[1] = new int[29];...

A jagged array is an array where each element is an array.

Page 13: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Initialize a Jagged Arrayint[][] highScores = new int[12][];

int[] days = new int[] { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

for (int month = 0; month < highScores.GetLength(0); ++month){ highScores[month] = new int[days[month]];

for (int day = 0; day < highScores[month].Length; ++day) { highScores[month][day] = MIN_HIGH_SCORE; }}

Page 14: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

The params keyword

int avg = CalculateAverage(5, 8, 32, 17, 9, 26);

We can gather method arguments into an array.

int CalculateAverage(params int[] values){ int sum = 0; foreach (int value in values) { sum += value; } return sum / values.Length;}

Page 15: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Working with Arraysstring[] lastNames = new string[] { “Smith”, “Newton”, “James”, “Wells”, “Alexander”, “Milton”, “Cooper”, “Ashe”, “Horton” };

int index = Array.BinarySearch(lastNames, “B”);

Array.Sort(lastNames);

// Copy all the names up to “B”string[] aNames = new string[~index];Array.Copy(lastNames, aNames, ~index);

Page 16: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Binary Search

Example of performing a binary search

Page 17: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

When to Use Arrays?

What are some things we might model using arrays?

Icons on your phone Security cameras around an office Playlists Distribution list on an email

Page 18: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Key Ideas for Arrays

Fixed length group of values or objects Access individual elements by index Use foreach to iterate over the array Use Length for one-dimensional arrays Use getLength() for rectangular

arrays Tip: Define constants for array lengths Tip: Define constants for initial values

Page 19: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Limitations of Arrays

Do you see any potential issues with using arrays?

Arrays can’t grow or shrink as needed

Page 20: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Collections Offer Flexibility Dynamically sized group of elements Better resource management Usually best choice for varying number

of elements

Page 21: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Different Kinds of Collections

List<T>Efficient sequential accessInefficient inserting into middle of list

SortedList<T>Access values by keyInefficient sequential accessEfficient inserting into middle of list

Queue<T> and Stack<T>Specialized access

Page 22: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Working with List<T>List<string> lastNames = new List<string>();lastNames.Add(“Smith”);lastNames.Add(“Barnes”);lastNames.Add(“Kelly”);lastNames.Add(“Metcalf”);

List<int> ages = new List<int>();ages.Add(43);ages.Add(24);ages.Add(31);ages.Add(27);ages.Add(“thirty-three”); // compile error – not int

lastNames.Sort(); // instance method for List<T>

Page 23: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Searching a List<T>

BinarySearch() requires Sort() BinarySearch() returns index or bitwise

complement of insertion point

lastNames.Sort();int index = lastNames.BinarySearch(“B”);

Page 24: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Working with SortedList<T>

// Create a collection of string values that we// can associate with int keys:

SortedList<int, string> classes = new SortedList<int, string>();

classes.Add(1006, “ASP.NET Fundamentals”);classes.Add(1007, “ASP.NET Advanced”);classes.Add(1002, “C#: Introduction for Developers”);classes.Add(1003, “Java Programming”);

// Access string value by int key:

string className = classes[1002];

Page 25: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Queues and Stacks

Queues and stacks define a strict ordering for how elements are added and removed

Queues are First-In-First-Out (FIFO)Like trains cars going through a tunnelThe tunnel is the queue and the cars are the

elements of the queueThe cars exit the tunnel in the same order

they entered the tunnel

Page 26: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Queues and Stacks

Stacks are Last-In-First-Out (LIFO)Like a shirts stacked in a drawerNew shirts go on top of the stackThe shirt on top is always the next one

removed from the stack Elements are discarded after retrieval

Page 27: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Count vs. Capacity

Capacity doubles when a collection outgrows its current capacity

Why might this be important to remember?

Set an initial capacity just above what you expect to use

Count = 11, Capacity = 16

Create a List<T> and add 13 elements

Page 28: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Untyped Collections

ArrayList is an untyped collection

// You can put any type of element into the array.

ArrayList list = new ArrayList();list.Add(5);list.Add(“Hello”);list.Add(4.3);

// But you need to cast it to the correct type when// removing it from the array.

int iValue = (int) list[0];string sValue = (string) list[1];decimal dValue = (decimal) list[2];

Page 29: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Choosing a Collection Class Raffle tickets Restaurant ordering system Track web site visitors over the last

seven days Online shopping cart Calculator

http://bit.ly/cs08-calc

Page 30: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Some Additional Collections Dictionary<TKey, TValue>

Unique keys NameValueCollection

Allows multiple values per key Hashtable BitArray, BitVector32

For working with bit flags LinkedList<T> Which collection should I use?

See http://bit.ly/cs08-selcol

Page 31: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Immutable Collections

.NET 4.5 contains the ImmutableList<T> class for use across threads

This…myList = myList.Add(anotherItem);

Instead of this…myList.Add(anotherItem);

Page 32: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Name Sorting Exercise Create a new project in your folder on S: Create a form that will accept a name in a

TextBox Use a button to read the name and add it to a list Create a Multiline, ReadOnly TextBox that will

display the list of names, sorted in alphabetical order

What input will be invalid? How will you handle invalid

input?

Page 33: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

CHAPTER 9

WORKING WITH DATES AND TIMES

Page 34: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

DateTime ObjectsDateTime when = new DateTime(2014, 1, 16, 18, 0, 0, 0);when = DateTime.Parse("2014-01-16T18:00:00-6:00");when = DateTime.Parse("2014-01-16 18:00:00");when = DateTime.Parse("Fri, 17 Jan 2014 00:00:00 GMT");when = DateTime.Parse("01/16/2014 6:00pm");when = DateTime.Parse("1/16/14 6pm");when = DateTime.Parse("Jan 16 2014");when = DateTime.Parse("6pm");

Stored internally as “ticks” since 01/01/0001 00:00 (DateTime.MinValue) 1 tick = 100 nanoseconds We should be okay until 12:00am on January 1, 10000

(DateTime.MaxValue)

Page 35: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

What time is it?

// Current date and timeDateTime now = DateTime.Now;

// Current date, 12:00AMDateTime today = DateTime.Today;

Page 36: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Displaying Date and TimeDateTime now = DateTime.Now;string text = now.ToLongDateString();text = now.ToShortDateString();text = now.ToLongTimeString();text = now.ToShortTimeString();

Date and time are formatted according to the operating system settings.

Page 37: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

DateTime Properties Date Month Day Year Hour Minute Second TimeOfDay DayOfWeek DayOfYear

Page 38: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Using DateTime Propertiesif ((myDoB.Month == yourDob.Month) && (myDob.Day == yourDob.Day)){ // What a happy coincidence!}

if ((today.DayOfWeek == DayOfWeek.Saturday) || (today.DayOfWeek == DayOfWeek.Sunday)){ Relax();}

Page 39: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

DateTime Methods

DaysInMonth(year, month) IsLeapYear(year)

Page 40: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Finding Relative Date and Time

DateTime expiration = DateTime.Now.AddDays(30); DateTime maturity = dob.AddYears(18); DateTime snooze = DateTime.Now.AddMinutes(5);

Add a negative value to subtract. These methods create a new DateTime object. The original

DateTime object is unchanged.

Page 41: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

TimeSpan ObjectsDateTime classTime = new DateTime(2014, 7, 15, 18, 0, 0);DateTime now = DateTime.Now;

TimeSpan freeTime = classTime – now;if (freeTime.TotalMinutes <= 0){ Panic();}if (freeTime.TotalMinutes <= 15){ Alert();}

Page 42: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Minutes vs. TotalMinutesTimeSpan span = TimeSpan.FromMinutes(75);

// This is true...if (span.Minutes < 30){

// 1 hour, 15 minutes}

// This is false...if (span.TotalMinutes < 30){}

Page 43: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Date Picker Exercise

Create a new project in your folder on S: Create a form that will accept date input

in a TextBox or DateTimePicker Create Labels that will display the

number of years and days that have elapsed since a selected date

Did you get any unexpected

results?

Page 44: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

CHAPTER 9, PART 2

WORKING WITH STRINGS

Page 45: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

What can we do with a string?

string alphabet = "abcdefghijklmnopqrstuvwxyz";

char m = alphabet[13];int letters = alphabet.Length;

foreach (char letter in alphabet){}

bool startsWell = alphabet.StartsWith("abc");bool endsWell = alphabet.EndsWith("xyz");

int x = alphabet.IndexOf("xyz");int x = alphabet.IndexOf('x');int x = alphabet.LastIndexOf('x');

Page 46: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Insert, Remove, and Replace

string alphabet = "abcdefghijklmnopqrstuvwxyz";

int l = alphabet.IndexOf("lmnop");string abbrev = alphabet.Remove(l, 5);string complete = abbrev.Insert(l, "lmnop");

string mixedCase = alphabet.Replace("abc", "ABC");

string beginning = alphabet.Substring(0, 6);string ending = alphabet.Substring(20);

Page 47: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Splitting Strings string numbers = "15,236,98,3,67";

string[] split = numbers.Split(',');

foreach (string number in split) { }

Page 48: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Trimming Strings Remove leading and trailing

whitespacestring greeting = " Hi, Steve. ";greeting = greeting.Trim();// greeting = "Hi, Steve."

Remove specific charactersstring numberList = "5,12,19,32,9, ,";char[] trimChars = { ',', ';', ' ' };numberList = numberList.Trim(trimChars);// numberList = "5,12,19,32,9"

Also, TrimStart() and TrimEnd()

Page 49: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

UPDATING THE FUTUREVALUE

EXAMPLE

Page 50: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Improved Input Handling

Update the example program to accept input that includes “$” and “%” if they occur in the appropriate location within the input data.

Look at example on p. 269.

Page 51: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

StringBuilder Manipulating and modifying string objects

can be inefficient.

string objects are immutable newstring = oldstring.Insert(0, 5); newstring = oldstring.Substring(0, 5);

StringBuilder objects are mutable StringBuilder b = new StringBuilder(); b.Append("Hello."); b.Append("My Name is Neal."); string greeting = b.ToString();

Page 52: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Useful Here…string[] lotsOfStringParts;

string appended = "";foreach (string part in lotsOfStringParts){ appended += part;}

StringBuilder b = new StringBuilder();foreach (string part in lotsOfStringParts){ b.Append(part);}string appended = b.ToString();

Page 53: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Not Here…string firstName;string lastName;

string fullName = firstName + " " + lastName;

StringBuilder b = new StringBuilder();b.Append(firstName);b.Append(" ");b.Append(lastName);string fullName = b.ToString();

Page 54: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Formatting NumbersString.Format(formatStr, value1, value2, ...);

Ex. “Hello, my name is {0}.“ { index [ ,width ] [ :format [ ; negative_format [; zero_format ] ] ] }

Formats: c[x]: Currency to x decimal places d[x]: Integer containing x digits e[x]: Scientific notation to x decimal places f[x]: Decimal number to x decimal places g[x]: Most compact number format between e and f n[x]: Number with thousands separator to x decimal places p[x]: Percentage to x decimal places (multiplies by 100)

balance = String.Format("{0:$#,##0.00;($#,##0.00)}", val);

Page 55: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

Formatting DatesString.Format(formatStr, value1, value2, ...);

Formats: d: Short date D: Long date t: Short time T: Long time f: Long date, short time F: Long date, long time g: Short date, short time G: Short date, long time

balance = String.Format(“Date:{0:d} Time:{0:t}", DateTime.Now);

Page 56: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

String Exercise #1

Create a new project in your folder on S: Create a form that will accept a phone

number input in a TextBox Create a ReadOnly TextBox that will

display the phone number in a standard form (i.e. (xxx) xxx-xxxx or xxx-xxx-xxxx)

What input will be invalid? How will you handle invalid

input?

Page 57: Neal Stublen nstublen@jccc.edu. Tonight’s Agenda  Arrays and collections  Dates and times  String methods  Q&A

String Exercise #2 Create a new project in your folder on S: Create a form that will accept a sequence of

numbers in a TextBoxe.g. “5,37,16,42,103,88”

Create a Multiline, ReadOnly TextBox that will display the list of numbers, sorted from smallest to largest

What input will be invalid? How will you handle invalid

input?