You are on page 1of 35

3/26/2010

CHNG 1:
N TP CC LP C S
A D M I N T U T H O C L A PT R I N H. C O M

NI DUNG
2

Chui v biu thc chnh quy ( regular expression)


Nhm i tng bao gm: danh sch mng,collections v

t in

3/26/2010

1.1 System.object
Phng thc

Mc ch

Truy xut

string ToString()

public virtua l

int GetHashCode()

public virtua l

bool Equals(object obj)

public virtua l

ool Equals(object objA,


object objB)

public static

bool
ReferenceEquals(obje ct
objA, object objB )

public static

Type GetType( )

Tr v 1 chui i din cho i


tng
Cho php nhng i tng cung
cp ring nhng hm bm cho s
dngtp hp.
So snh i tng bng vi 1 i
tngkhc
So snh bng 2 i tng
So snh cc tham chiu i tng
xem chng c ch n cng i
tng
Tr v 1 i tng dn xut t
System.Type m a ra chi tit
kiu d liu

public

object MemberwiseClone()
void Finalize()

To mt bn sao t i tng

protected
protected virtual

Mc ch

Phng thc

Hm hy ( Destructor)

Compare

So snh ni dung ca 2 chui

CompareOrdinal

Ging compare nhng khng quan tm n ngn ng

Format

nh dng mt chui cha 1 gi t r khc v ch nh


cch mi g i tr nn c nh dng.

IndexOf

1.2 X Vltrchui
xut h in (System.string)
u tin ca 1 chui con hoc k t trong
chui

Phng thc
IndexOfAny
string ToString()

LastIndexOf

V tr Truy
xut hin
1 hoc
xut u tin ca bt kMc
ch1 tp k t
trong chui
Tr
v
1
chui
i din cho i
public virtua l
tng

Ging indexof , nh ng tm ln
in cui
Choxut
phph nhng
icng
tng cung

int GetHashCode()
specifier
type
bool Equals(object obj)

cp ring nhng hm bm cho s

public virtua l

output dngtp hp.


output
format
bng vi
(double
1.23 So
45) snh i tng
(int -12345)
public virtua
l

1 i

tngkhc

currency
1.23
-12,345.00
oolc Equals(object
objA,{0:c}
public static
So snh bng 2 i tng
object objB)
decim al
{0:d}
System.Format Exception
-12345
boold
So snh cc
tham chiu i tng
(whol e number)
public static
ReferenceEquals(obje ct
xem chng c ch n cng i
exponentobjB
/ scienti
1.234500e+0 00
objAe , object
) fi c {0:e}
tng -1.234500e+0 04
f
fixed point
Type GetType( )
g
general

{0: f}
{0:g}

Tr v 1-12345.00
i tng dn xut t
System.Type m a ra chi tit
-12345
kiu d liu

1.23
public
1.2345

n
number
{0:n}
1.23
-12,345.00
object MemberwiseClone()
protected
To mt bn
sao t i tng
r
round trippabl e
{0:r}
1.23
System.Format Exception
void Finalize()
protected virtual
Hm hy ( Destructor)
x
hexadecimal
{0:x4}
System.Format Exception
ffffc fc7

Phng thc

K t

Compare
\w

Mc ch

ngha

So snh
ni
cadu
2 chui
K t word (gm
ch ci
vdung
ch s,
gch di _ ) tngng [a-zAZ_0-9]

CompareOrdinal

Ging compare nhng khng quan tm n ngn ng

3/26/2010

1.2 X l chui (System.string)


5

Mc ch

Phng thc
LastIndexOfAny

Ging indexofAny , nhng tm ln xut hin cui cng


Canh phi chui in chui bng cch thm 1 k t c
ch nh lp li vo u chui
Canh tri chui in chui bng cch thm 1 k t c
ch nh lp li vo cui chui
Thay th k t hay chui con trong chui vi 1 k t
hoc chui con khc
Chia chui thnh 2 mng chui con, ngt bi s xut
hin ca mt k t no
Tr v chui con bt u mt v tr ch nh trong
chui.
Chuyn chui thnh ch thung
Chuyn chui thnh ch in
B khong trng u v cui chui

PadLeft
PadRigth
Replace
Split
Substring
ToLower
ToUpper
Trim

1.2 X l chui (System.string)


6

V d:

Compare

string str1 = "ppp";


string str2 = "ccc";
int res = String.Compare(str1, str2);
Console.WriteLine("First result:" +res.ToString());
str2 = "ttt";
res = String.Compare(str1, str2);
Console.WriteLine("Second result:" +res.ToString());
str1 = "ttt";
res = String.Compare(str1, str2);
Console.WriteLine("Third result:"+res.ToString());

3/26/2010

1.2 X l chui (System.string)


7

V d: Format

Phng thc

Mc ch

Truy xut

string ToString()

public virtua l

int GetHashCode()

public virtua l

bool Equals(object obj)

public virtua l

ool Equals(object objA,


object objB)

public static

bool
ReferenceEquals(obje ct
objA , object objB )

public static

Type GetType( )

Tr v 1 chui i din cho i


tng
Cho php nhng i tng cung
cp ring nhng hm bm cho s
dngtp hp.
So snh i tng bng vi 1 i
tngkhc
So snh bng 2 i tng
So snh cc tham chiu i tng
xem chng c ch n cng i
tng
Tr v 1 i tng dn xut t
System.Type m a ra chi tit
kiu d liu

public

object MemberwiseClone()
void Finalize()

To mt bn sao t i tng

protected
protected virtual

Hm hy ( Destructor)

Mc ch

Phng thc
Compare

So snh ni dung ca 2 chui

CompareOrdinal

Ging compare nhng khng quan tm n ngn ng

1.2 X l
chui (System.string)
nh dng mt chui cha 1 gi t r khc v ch nh

Format

cch mi g i tr
8 nn c nh dng.

double d = 1.2456d; V tr xut h in u tin ca 1 chui con hoc k t trong


IndexOf
string str = String.Format("{0:c}",
d);
chui
Console.WriteLine(str);
V tr xut d);
hin u tin ca bt k 1 hoc 1 tp k t
str = String.Format("{0:f}",
IndexOfAny
trong
chui
Console.WriteLine(str);

LastIndexOf
string chuoi0 1

= "ppp"; Ging indexof , nh ng tm ln xut h in cui cng


object objClone = chuoi01.Clone();
Console.WriteLine("Clon e :"+objClone.ToString());
output
output
specifier
type
format
(double 1.2345)
(int -1 2345)
string str1 = "ppp" ;
string str2 = "ccc" ;
c
currency
{0:c}
1.23
-12,3 45.00
string str 3 = "kkk";
string []decim
allStr
=
ne
w
String
[]{str1,
str2
,
str3};
al
d
{0:d}
-12345
string
strRes = String .Jo
in( ", ", System.Format
allStr) ; Exception
(whol e number)
Console.WriteLine("Join Results : "+ strRes);
e

exponent / scienti fi c

{0:e}

1.234500e+000

-1.234 500e+0 04

fixed point

{0: f}

1.23

-12345.00

general

{0:g}

1.2345

-12345

number

{0:n}

1.23

-12,34 5.00

round trippabl e

{0:r}

1.23

System.Format Exception

hexadecimal

{0:x4}

System.Format Exception

ffffc fc7

3/26/2010

1.2 X l chui (System.string)


string str = "forty-two";
char pad = '.';

Console.WriteLine(str.PadLeft(15, pad));
Console.WriteLine(str.PadLeft(2, pad));
Console.WriteLine(str.PadRight(15, pad));
Console.WriteLine(str.PadRight(2, pad));

string str = "forty- two";


string [] arr = str.Split('-' );
foreach (string s in arr)
Console.WriteLine(s) ;
string aStr = "adgas";
string bStr = "ABNMDWER";
string strRes = aStr.ToUpper();
Console.WriteLine("Uppercase:"+ strRes.ToString());
strRes = bStr.ToLower();
Console.WriteLine("Lowercase:"+ strRes.ToString());
strRes = aStr.Replace('a', 'b');
Console.WriteLine("Replaced string:" + strRes.ToString());

1.3 Biu thc chnh quy ( Regular Expression)


10

Ngn ng biu thc chnh quy l ngn ng c thit k c bit cho vic
x l chui. C 2 c tnh :
tp m escape cho vic xc nh kiu ca cc k t . V d vic dng k t *
trnh by chui con bt k trong biu thc DOS , biu thc chnh quy dng nhiu
chui nh th trnh by cc mc nh l 'bt k 1 k t' ,'1 t ngt ','1 k t tu
chn',...
1 h thng cho vic nhm nhng phn chui con, v tr v kt qu trong sut thao
tc tm.
1

Dng biu thc chnh quy c th thao tc cp cao v phc tp trn chui:
nh tt c cc t lp li trong chui , chuyn "The computer books books"
"The computer books"
Chuyn tt c cc t theo title case, nh l chuyn "this is a Title" "This Is A
Title".
Chuyn nhng t di hn 3 k t thnh title case , v d chuyn "thi s is a Title
"This is a Title
Xc

Bo m cc cu c vit hoa
Phn cch nhng phn t ca URL

3/26/2010

1.3 Biu thc chnh quy ( Regular Expression)


11

V d: Tm tt c cc v tr xut hin ca mt chui trong chui khc


string Text = "Xin chao cac ban. Chao";
string Pattern = "ao";
MatchCollection Matches = Regex.Matches(Text, Pattern,
RegexOptions.IgnoreCase);
foreach (Match NextMatch in Matches)
{
Console.WriteLine(NextMatch.Index);
} //Xu t r a mn hnh: 6
20

dng Regex.Matches(Text, Pattern,


RegexOptions.IgnoreCase|RegexOptions.ExplicitCapture);
Text l chui
Pattern l chui a vo tm kim trong Text

RegexOptions.IgnoreCase: khng phn bit hoa


thng

1.3 Biu thc chnh quy ( Regular Expression)


12

K t
^

ngha
Bt u ca chui nhp

V d
^B

Kt thc ca chui nhp

X$

Bt k k t no ngoi tr k t
xung dng(\n)
K t trc c th c lp li 0
hoc nhiu ln
K t trc c th c lp li 1
hoc nhiu ln
K t trc c th c lp li 0
hoc 1 ln
Bt k k t khong trng

*
+
?
\s

.ation
ra*t
ra+t
ra?t
\sa

Mt s th hin
B, nh ng ch nu k t
u tin trong chui
X, nhng ch nu k t
cui cng trong chui
isation, izat ion
rt, rat, raat, raaat, and so
on
rat, raat , raaat and so on,
(but not rt)
rt and rat only
[space]a, \ta, \na (\t and
\n c ngha ging nh
trong C#)

3/26/2010

1.3 Biu thc chnh quy ( Regular Expression)


13

Phng thc

Mc ch

Truy xut

string ToString()

public virtua l

int GetHashCode()

public virtua l

bool Equals(object obj)

public virtua l

ool Equals(object objA,


object objB)

public static

bool
ReferenceEquals(obje ct
objA , object objB )

public static

Type GetType( )

Tr v 1 chui i din cho i


tng
Cho php nhng i tng cung
cp ring nhng hm bm cho s
dngtp hp.
So snh i tng bng vi 1 i
tngkhc
So snh bng 2 i tng
So snh cc tham chiu i tng
xem chng c ch n cng i
tng
Tr v 1 i tng dn xut t
System.Type m a ra chi tit
kiu d liu

public

object MemberwiseClone()
void Finalize()

To mt bn sao t i tng

protected
protected virtual

Hm hy ( Destructor)

Mc ch

Phng thc
Compare

So snh ni dung ca 2 chui

CompareOrdinal

Ging compare nhng khng quan tm n ngn ng

nh dng mt chui cha 1 gi t r khc v ch nh


1.3 Biu thc chnh
quy ( Regular Expression)
cch mi g i tr nn c nh dng.

Format

14
K t

IndexOf
|

ngha
V tr xut h in u
tin ca 1 chui con hoc k t trong
chui
K t ngn cch so trngtngng vi php or (lu ci ny nu

mun kt hp
iu kin)
Vnhiu
tr xut
hin u tin ca bt k 1 hoc 1 tp k t
Khp vi 1 k
t
nm
trong nhm l a hay b hay c.
trong chui
So trng vi 1 k t nm trong phm vi a-z, dng du - lm du ngn
cch.
LastIndexOf
Ging indexof , nh ng tm ln xut h in cui cng
S khng so trng vi 1 k t nm trong nhm, v d khng so trngvi a
[^abc]
hay b hay c.
output
output
Xc nh 1 group
(biu thc con) xem
nh n l mt yu t n
l trong
()
specifier
type
format
(double 1.2345)
(int -1 2345)
pattern .
V d: ((a(b))c)
s khp vi
b, ab, abc.
c
currency
{0:c}
1.23
-12,3 45.00
n l con s, Khp ng vi n k t ng trc n .
{n}
decim al V d A{2}: khp ng vi 2 ch A.
d
{0:d}
System.Format Exception
-12345
Khp ng vi n k t tr ln ng trc n ,
{n, } (whol e number)
A{2,} khp vi AA, AAA ...
e
exponent / scienti fi c {0:e}
1.234500e+000
-1.234 500e+0 04
Khp ng vi t m->n k t ng trc n,
{m,n }
A{2,4}
khp
vi
AA,AAA,AAAA.
f
fixed point
{0: f}
1.23
-12345.00

IndexOfAny
[abc]
[a-z]

general

{0:g}

1.2345

-12345

number

{0:n}

1.23

-12,34 5.00

round trippabl e

{0:r}

1.23

System.Format Exception

hexadecimal

{0:x4}

System.Format Exception

K t

ngha

ffffc fc7

3/26/2010

1.3 Biu thc chnh quy ( Regular Expression)


15

// This is the input string.


string input = "/content/alternate-1.aspx";
// Here we lowercase our input first.
input = input.ToLower();
Match match = Regex.Match(input, @"content/([AZa-z0-9\-]+)\.aspx$");
Console.WriteLine( "\"{0}\" chuoi khop",match);

1.3 Biu thc chnh quy ( Regular Expression)


16

V d:
nh ngha biu thc chnh quy so khp tin t (USD).
// Define a regular exp ression for cur rency values.
Rege x r x = new Regex (@"^-?\d +(\.\d{2})?$?.USD");
// Define some test str ings.
string [] test s = { "-42", "1 9.99" , "0.001", "100 USD" };
// Chec k each tes t stri ng against the regular expression.
foreach (string test in tests)
{
if (rx.IsMatch(test) )
Console.WriteLine("{0} is a currency value.", test);
else
Console.WriteLine("{0} i s not a currency value.", test) ;
}

3/26/2010

1.3 Biu thc chnh quy ( Regular Expression)


17

Vit biu thc chnh quy so khp a ch web:

VD: http://www.wrox.com

Regex rx = new Regex(@"http://(\S+)(?::(\S+))?\b", RegexOptions.IgnoreCase);


string text = "http://www.wrox.com:4355";
Match m = rx.Match(text);
Console.WriteLine(m);

Biu thc ch nh quy kim tra s in thoi di ng


Biu thc ch nh quy kim tra a ch mail: yahoo.com v g mail.com
string mail = "ntluong1983@gmail.com " ;
string patter n = @"([A -Za-z\ d_]+)@((yahoo)|(gma il) )\.com";
Matc h matc h = Regex.Match (mail, pattern);
Console.WriteLine("\"{0}\" chuo i khop" , match);
string input = "09197792599" ;
pattern = @"([0-9]{10,11})";
matc h = Regex .Match(input, pattern);
Console.WriteLine("\"{0}\" chuo i khop" , match);

1.3 Biu thc chnh quy ( Regular Expression)


18

VD: Kim tra t trng nhau


// Define a regular expression for repeated w ords.
Regex rx = new Regex(@"\b( ?<word>\w+)\s +(\k<word >)\b",
RegexOptions.Compi led | RegexOptions.Ign oreCase);
// Define a test string.
string text = "The the quick brown fox fox jumped over the lazy dog dog";
// Find matches.
MatchCollection matches = rx.Matches(text) ;
// Report the number of matches found.
Console.WriteLine(" {0} matches found in: \n
{1}",
matches.Count,
text);
// Report on each ma tch.
foreach (Match match i n matches)
{
GroupCollection groups = match .Groups;
Console.WriteLine(" '{0}' repeat ed at positions {1} and {2}",
groups["word"].Val ue,
groups[0].Index,
groups[1].Index);
}

3/26/2010

1.4 Nhm cc i tng


19

1.4.1 Array lists

System.Collection.Arraylist
Phng thc

string ToString()

public virtua l

int GetHashCode()

public virtua l

bool Equals(object obj)

public virtua l

ool Equals(object objA,


object objB)

public static

bool
ReferenceEquals(obje ct
objA , object objB )

public static

Type GetType( )

Tr v 1 chui i din cho i


tng
Cho php nhng i tng cung
cp ring nhng hm bm cho s
dngtp hp.
So snh i tng bng vi 1 i
tngkhc
So snh bng 2 i tng
So snh cc tham chiu i tng
xem chng c ch n cng i
tng
Tr v 1 i tng dn xut t
System.Type m a ra chi tit
kiu d liu

public

object MemberwiseClone()
void Finalize()

To mt bn sao t i tng

protected
protected virtual

Hm hy ( Destructor)

Mc ch

Phng thc
Compare
CompareOrdinal

Mc ch

Truy xut

So snh ni dung ca 2 chui

1.4 Nhm
cc i tng
Ging compare nhng khng quan tm n ngn ng
20

nh dng mt chui cha 1 gi t r khc v ch nh


1.4.1 Array lists: System.Collection.Arraylist
Format
cch mi g i tr nn c nh dng.
Phng thc
Truy xut
Mc ch
Tr v 1 chui i din cho i

string ToString()

l tin ca 1 chui con hoc k t trong


V public
tr xut hvirtua
in u
tng
chui
Cho php nhng i tng cung

int GetHashCode()

l
cp bt
ringknhng
hm
chots
V public
tr xutvirtua
hin u
tin ca
1 hoc
1 bm
tp k
dngtp
hp.
trong chui

IndexOf

IndexOfAny
bool Equals(object obj)

LastIndexOf

ool Equals(object objA,


object objB)
bool
specifier
type
ReferenceEquals(obje ct
objAc, object
objB )
currency
decim al)
Type GetType(
d
(whol e number)

Ging indexof , nh ng tm ln xut h in cui cng

gPhng
general
thc
n
number
Compare

So snh bng 2 i tng

public static
output

output
So snh cc tham chiu i tng
format
(double
1.2345)
(int
-1 2345)
public static
xem chng c ch n cng i
{0:c}
{0:d}

object
e
MemberwiseClone()
exponent / scienti fi c {0:e}
fixed point
voidf Finalize()

So snh i tng bng vi 1 i


tngkhc

public virtua l

tng
-12,3 45.00
Tr v 1 i tng dn xut t
public
System.Type
m a ra chi tit
System.Format Exception
-12345
kiu d liu
1.23

protected
1.234500e+000

{0:protected
f}
1.23
virtual
{0:g}
{0:n}
So snh

1.2345

-1.234
To mt bn
sao500e+004
t i tng

Hm hy (-12345.00
Destructor)

Mc ch

ni1.23
dung ca 2 chui

-12345
-12,34 5.00

10

3/26/2010

1.4 Nhm cc i tng


21

1.4.1 Array lists: System.Collection.Arraylist


Phng thc

Mc ch

Truy xut

string ToString()

public virtua l

int GetHashCode()

public virtua l

bool Equals(object obj)

public virtua l

ool Equals(object objA,


object objB)

public static

bool
ReferenceEquals(obje ct
objA , object objB )

public static

Type GetType( )

public

object MemberwiseClone()
void Finalize()

protected
protected virtual

Tr v 1 chui i din cho i


tng
Cho php nhng i tng cung
cp ring nhng hm bm cho s
dngtp hp.
So snh i tng bng vi 1 i
tngkhc
So snh bng 2 i tng
So snh cc tham chiu i tng
xem chng c ch n cng i
tng
Tr v 1 i tng dn xut t
System.Type m a ra chi tit
kiu d liu
To mt bn sao t i tng
Hm hy ( Destructor)

Mc ch

Phng thc
Compare

So snh ni dung ca 2 chui

CompareOrdinal

Ging compare nhng khng quan tm n ngn ng

1.4 Nhm cc i tng

Format

1.4.1 Array lists:

Phng thc
IndexOf

nh dng mt
22 chui cha 1 gi t r khc v ch nh
cch mi g i tr nn c nh dng.
System.Collection.Arraylist
V tr xut h in u tin ca 1 chui con hoc k t trong
Truy xut
Mc ch
chui

string ToString()

public virtua l

Tr v 1 chui i din cho i

tngbt k 1 hoc 1 tp k t
V tr xut hin u tin ca
Cho php nhng i tng cung
trong chui

IndexOfAny

cp ring nhng hm bm cho s


LastIndexOf
Ging indexof , nh ng tm dngtp
ln xuthp.
h in cui cng
So snh i tng bng vi 1 i
bool Equals(object obj)
public virtua l
tngkhc
int GetHashCode()

public virtua l

ool
Equals(object
specifier
type objA,
object objB)
boolc
currency
ReferenceEquals(obje ct
decim alobjB )
objAd, object
(whol e number)
Typee GetType(
) / scienti fi c
exponent

output
format
public static
(double 1.2345)
So snh

-12,3
45.00
So snh cc
tham
chiu i tng
xem chng c ch n cng i
tng
System.Format Exception
-12345
Tr v 1 i tng dn xut t
public
m
a ra chi tit
1.234500e+000 System.Type
-1.234
500e+004
kiu d liu

{0:c}
1.23
public static
{0:d}
{0:e}

f
fixed point
{0: f}
1.23
object MemberwiseClone()
protected
g
general
{0:g}
1.2345
void Finalize()
protected virtual
n
number
{0:n}
1.23

Phng thc

round trippabl e

Compare

output

bng 2 i
(inttng
-1 2345)

{0:r}

1.23

-12345.00

To mt bn sao t i tng
-12345

Hm hy ( Destructor)

Mc ch

So snh ni dung ca 2 chui

-12,34 5.00

System.Format Exception

11

3/26/2010

V d: ArrayList
23

ArrayList list = new ArrayList();


list.Add("fish");
list.Add("amphibian");
list.Add("bird");
list.Add("plant");
Console.WriteLine("Count of List:" + list.Count);//Display: 4
// Get two elements in ArrayList.
ArrayList range = list.GetRange(1, 2);
// Display the elements of range
foreach (string value in range)
Console.WriteLine(value); // Display: amphibian, bird
list.Reverse();//Reverse elements of list
foreach (string s in list)
Console.WriteLine(s);//Display: plant,bird,amphibian, fish
list.Sort();//sort elements of list
foreach (string s in list)
Console.WriteLine(s);//Display:amphibian,bird,fish, plant

V d: ArrayList
24

list.Add("fish");
Console.WriteLine("Index of \"fish\":"+list.IndexOf("fish"));
list.Remove("fish");//Remove "fish" the fist out of list
foreach (string s in list)
Console.WriteLine(s);//Display: amphibian,bird,plant,fish
list.Clear();
Console.WriteLine("count of list:" + list.Count);//Display:0
Console.WriteLine("Index of \"fish\":"+list.IndexOf("fish"));
list.Remove("fish");//Remove "fish" the fist out of list
foreach (string s in list)
Console.WriteLine(s);//Display: amphibian,bird,plant,fish
string [] arra y = list.ToArray(typeof (string)) as string[];
//Loop ove r array .
foreach (string valu e in array)
Console.WriteLine(value);

//Display: amphibian,bird,plant,fish

list.Clear();
Console.WriteLine("count of list:" + list.Count);//Display:0

12

3/26/2010

1.4 Nhm cc i tng


25

1.4.2. Collection
1 i tng l 1 collection nu n c th cung cp 1 tham chiu n
mt i tng c lin quan, c bit n nh l enumarator, m c
th duyt qua tng mc trong collection. c bit, 1 collection phi
thi hnh 1 interface:

System.Collections.Ienumerable
interface IEnumera ble
{
IEnumerator GetEnumerator() ;
}

Mc ch ca GetEnu marator() l tr v i tng enumarator. Khi ta


tp hp nhng on m trn i tng enumarator c mong i thi
hnh 1 interface, System.Collections.IEnu merator.

1.4 Nhm cc i tng


26

1.4.2. Collection

Ngoi ra cn c mt interface khc , Icollection , c dn xut t


IEnu merable. IEnu marator c cu trc sau:
i nt e r fa c e I E n um e r at o r
{
o bj e c t C u r re n t { g e t ; }
b oo l M ov e N ex t ( );
v oi d R es e t () ;
}

Khi to i tng (collection) c to th n cha tr n phn t no trn


collection v vy phi gi MoveNext() t r n phn t u tin.
Ly phn t gi Current

13

3/26/2010

1.4 Nhm cc i tng


27

1.4.2. Collection

V d: vi string
string[] MessageSet = new string[3];
MessageSet[0] = "Hello";
MessageSet[1] = "Good bye";
IEnumerator enumerator = MessageSet.GetEnumerator();
string nextMessage;
enumerator.MoveNext();
while ((nextMessage = enumerator.Current as string) !=
null)
{
Console.WriteLine(nextMessage);
// toNextMessage
enumerator.MoveNext();
}

1.4 Nhm cc i tng


28

To Collection cho Tokens

14

3/26/2010

/ / I nn e r cl a s s i m p le m e nt s I E nu m e ra t o r in t e rf a c e:
p ub l i c c l as s To k e nE n u me r a to r : I En u m er a t or
{
p ri v a te i n t p o s it i o n = - 1 ;
p ri v a te T o ke n s t;
p ub l i c T o k en E n um e r at o r (T o k en s t)
{
t hi s . t = t ;
}
/ / D e c la r e th e M ov e N ex t m et h o d re q u ir e d by I En u m e ra t o r:
p ub l i c b o o l M o v eN e x t ()
{
i f ( p os i t io n < t . e le m e nt s . Le n g th - 1 )
{
p os i t io n + +;
r et u r n t r u e;
}
e ls e
{
r et u r n f a l se ;
}
}
/ / D e c la r e th e R es e t me t h od r e qu i r ed b y IE n u me r a t or :
p ub l i c v o i d R e s et ( )
{
p os i t io n = - 1 ;
}
/ / D e c la r e th e C ur r e nt p r op e r ty r e q ui r e d b y IE n u m er a t or :
p ub l i c o b j ec t C ur r e n t
{
g et
{
r et u r n t . e le m e nt s [ po s i ti o n ];
}
}
}
29

public class Tokens : IEnumerable


{
public string[] elements;
Tokens(string source, char[] delimiters)
{
// Parse the string into tokens:
elements = source.Split(delimiters);
}
// IEnumerable Interface Implementation:
//
Declaration of the GetEnumerator() method
//
required by IEnumerable
public IEnumerator GetEnumerator()
{
return new TokenEnumerator(this);
}
}

30

15

3/26/2010

static void Main()


{
//Testing Tokens by breaking the string into tokens:
Tokens f = new Tokens("This is a well-done program.",
new char[] {' ', '-' });
IEnumerator enumerator = f.GetEnumerator();
string s;
while (enumerator.MoveNext())
{
s = enumerator.Current as string;
Console.WriteLine(s);
}
}

31

1.4 Nhm cc i tng


32

To Collection cho vector

16

3/26/2010

p ub l i c c l as s Ve c t or
{
f lo a t a ;
f lo a t b ;
f lo a t c;
p ub l i c V e c to r ( )
{
a = 0;
b = 0;
c = 0;
}
p ub l i c V e c to r ( in t a , in t b, i n t c )
{
t hi s . a = a ;
t hi s . b = b ;
t hi s . c = a ;
}
p ub l i c o v e rr i d e s t r i ng T o St r i ng ( )
{
r et u r n " ( " +a + " ," + b +" , " +c + " )" ;
}
}
pub li c c las s V ec to rs : I En um er abl e
{
pub li c V ec to r[ ] el em en ts ;
pub li c i nt nu m;
pub li c V ec to rs ()
{
ele me nt s = ne w Vec to r[ 3] ;
ele me nt s[ 0] = n ew Ve ct or (1 ,2 ,3) ;
ele me nt s[ 1] = n ew Ve ct or (2 ,2 ,2) ;
ele me nt s[ 2] = n ew Ve ct or (3 ,3 ,3) ;
num = 3;
}
pub li c I En um er at or G etE nu me ra to r()
{
ret ur n n ew Ve ct or En um era to r( th is );
}
}

p ub l i c c l as s Ve c t or E n um e r at o r : IE n u me r a to r
{
p ri v a te i n t p o s it i o n = - 1 ;
p ri v a te V e ct o r s v ;
p ub l i c V e c to r E nu m e ra t o r( V e ct o r s v )
{
t hi s . v = v ;
}
p ub l i c b o o l M o v eN e x t ()
{
i f ( p os i t io n < v . n um - 1 )
{
p os i t io n + +;
r et u r n t r u e;
}
e ls e r e t ur n f al s e ;
}
p ub l i c v o i d R e s et ( )
{
p os i t io n = - 1 ;
}
p ub l i c o b j ec t C ur r e n t
{
g et { re t u rn v . el e m en t s [p o s it i o n] ; }
}
s ta t i c v o id M ai n ( )
{
V ec t o rs v = ne w Ve c t or s ( );
I En u m er a t or e = v. G e tE n u me r a to r ( );
V ec t o r s ;
w hi l e (e . M ov e N ex t ( )) {
s = e .C u r re n t as V e c to r ;
C on s o le . W ri t e Li n e (s ) ;
}
}
}

33

1.4 Nhm cc i tng


34

T in trong .NET: S dng lp Hasthable


Hashtable employees = new Hashtable(53);

17

3/26/2010

class Employee
{
string Id;
string Name;
int Year;
public Employee(string id, string name, int year)
{
this.Id = id;
this.Name = name;
this.Year = year;
}
public override string ToString()
{
return Id + "\t" + Name + "\t" + Year;
}
}

Hashtable employees = new Hashtable(53) ;


//Insert Item to dictionary
employees.Add("001", new E mployee( "001", "Joh n", 1982)) ;
employees.Add("002", new Employee ("002","Marry", 1984)) ;
//Get item with Key
Console.WriteLine(employees[ "001"] as Employ ee);
Console.WriteLine(employees[ "002"] as Employ ee);
//Count items in dictionary
Console.WriteLine("Coun t:" + employees.Co unt);
//remove Item wit h Key
employees.Remove( "002");
Employee e=employees["00 2"] a s Employee;
if(e!= null)
35
Console.WriteLine(e) ;

18

You might also like