Tải bản đầy đủ - 0 (trang)
Chapter 4. Creating and Using .NET Collections

Chapter 4. Creating and Using .NET Collections

Tải bản đầy đủ - 0trang

4.0Introduction

Variablesarewellsuitedforholdingasinglepieceofdata,but

moreoftenthannot,youneedamechanismthatcanstore

morethanonepieceofdataofacertaintype.Collectionsallow

youtoplacedatawithinasinglecontainingobjectandretrieve

individualelementswithinthatcontainerusingaconsistent

retrievalmethod.Thischapterlooksathowcollectionsareused

withintheC#languageand.NETFramework.Becauseseveral

differentcollectiontypesarebuiltintothe.NETFramework,

you'llseehowtoselecttheappropriatecontainerbasedonyour

applicationdesign.Furthermore,youwillalsolearnhowto

createyourowncollectiontypesifnoothersuitablecontaineris

available.



4.1DeclaringandUsingArrays

Youwanttocreateasimplearrayofobjects,andyouknowexactlyhow

manyelementsthecollectionneeds.



Technique

Useasingledimensionarrayifyouwantacollectionofobjects

thatcanbeaccessedinalinearfashion.Thearraydatatypeis

thedatatypeoftheobjectsyouwanttoinsertintothearray,

followedbyleftandrightbrackets.Toinitializethearraywitha

setofvalues,assignthearrayvariabletoacomma-delimited

listofvaluessurroundedbyleftandrightbraces.



int[]arr1={1,2,3,4,5,6,7,8,9,10};

Ifyoudon'twanttoinitializetheelementsinthearraybut

wouldrathersettheindividualelementslater,usethenew

keywordonthecollectiondatatype,specifyingthearraysizein

brackets.



int[]arr2=newint[10];

Toaccessasingleelementinthearray,placetheindexofthe

elementyouwanttoaccessrelativetothebeginningofthe

arrayelement,whichhasanindexof0inbracketsfollowingthe

arrayvariablename:



staticvoidTestSingleDimensionArray()

{

int[]arr1={1,2,3,4,5,6,7,8,9,10};

int[]arr2=newint[10];



for(inti=0;i
{

arr2[i]=arr1[i];

Console.WriteLine(arr1[i]+"="+arr2[i]);

}

}

Ifyouwanttocreateanarraywithmorethanonedimension,



declarethevariableusingthedatatypetoplaceinthearray,

followedbybracketscontainingacommatoseparateeach

dimensionwithinthearray.Forinstance,atwo-dimensional

arrayusedtoholddatainrowsandcolumns,asshowninthe

TestMultiDimensionArraylisting,wouldcontainonecomma.

Tocreatethearraywithoutinitializingtheindividualelements,

usethesametechniqueforasingle-dimensionarraybutusea

comma-separatedlistdenotingthenumberofelementseach

dimensioncanhold:



staticvoidTestMultiDimensionArray()

{

string[,]arr1=newstring[10,10];



//assignvalues

for(introw=0;row<10;row++)

{

for(intcol=0;col<10;col++)

{

arr1[row,col]=row+","+col;

}



}



//printvalues

for(inti=0;i<10;i++)

{

for(intj=0;j<10;j++)

{

Console.Write(arr1[i,j]+"\t");

}

Console.WriteLine();

}

}

Tocreateaninitializedmultidimensionalarray,placeeach

dimension'svaluewithinleftandrightbracessimilartothe

initializationofasingle-dimensionarray,andplaceeach

dimension'selementlistwithinbracesalso.



int[,]identity={{0,1},{1,0}};



Comments

Arraysaresimplecollectionswhoseelementsyouaccessusing

indices.Becausetheiruseiswidespreadinavarietyofdifferent

programmingscenarios,C#createdspecialsyntactical

elementstoaidintheircreation,initialization,andelement

access.

Thedeclarationofanarrayconsistsofthedatatypeofthe

elementsyouwanttoplaceintothearrayfollowedbyasetof

bracketsandthevariablenameofthearray.Thesebrackets

specifyhowmanydimensionsanarrayhas.Adimensioninan

arrayisthesameasitsmathematicalcounterpart.Atwodimensionalarray,forinstance,containsagroupofelements

thatinturneachcontainagroupofelements.Areal-world

exampleisaspreadsheetthatcontainstwodimensions,arow

andacolumn.Althoughitmightbehardtothinkofdimensions

inthefifthorhigherdegree,youcaneasilycreatethemina

programminglanguagelikeC#.

Toaccessanindividualelementwithinanarray,youusean

indexer,whichisanintegervaluebetweenbracketsspecifying

thenumberorindexoftheelementyouwanttoaccess.Fora

single-dimensionarray,thereisoneindexvalueperarray

element.Foramultidimensionalarray,theindicesspecified

withinacomma-separatedlistcorrespondtotheelementat

eachlocationofthedimensioninwhichtheindexisplaced.For

instance,anelementwithinatwo-dimensionalarrayusesthe

format[x,y],wherexisanindexintothefirstdimensionandy

istheindexintotheseconddimension.Thislineinturnreturns

thevalueatthatlocation.

Amajoradvantagetousinganarrayoveranyothercollection

typeisthefastperformancewhenretrievinganelement.When

youcreateanarray,thememoryisallocatedasasingle

contiguousblockofmemory,regardlessofthenumberof

dimensionswithinthearray.Therefore,givenanindexvalue,



theCommonLanguageRuntime(CLR)caneasilyfindthe

correspondingelementbymultiplyingtheindexbythesizeof

theelement'sdatatypeandusingthatvalueasanoffsetfrom

thebeginningofthearray'smemoryblock.Theperformanceof

accessinganelementwithinanarraygivenanindexvalueruns

inconstantor0(1)time.

Althoughtheperformanceofelementaccesswithinanarrayis

certainlyfast,itstillrequiresthatyouknowtheindexofthe

elementyouwanttoaccess.Insomecases,thisrequirement

mightbeacceptable,butonceyoustartneedingfeaturessuch

asfindinganelement,theperformanceofusinganarraydrops.

Searchinganarrayforaspecificvaluerequiresthatthe

programaccesseveryelement,beginningwiththefirstindex

andcontinuinguntilitfindstheelementorreachestheendof

thearray.

Duetoitssimplenature,arraysalsohaveafewmore

drawbacks.Onceyoucreateanarray,youcannotaddelements

pastthesizesdeclaredforeachdimension.Inotherwords,an

arraycannotincreaseinsizenorcanitinsertelementsintothe

middle.Additionally,asingle-dimensionormultidimensionarray

canconsumelargeamountsofmemory,evenifyoudonot

placevaluesinthearray.Forsmallarrays,thispointisamoot,

butlargemultidimensionalarraysreservelargeportionsof

memory,evenifyoudon'tplacevaluesintothearrayelements.



4.2DefiningJaggedArrays

Youwanttocreateanarrayofarrays,eachwithdifferent

dimensions.



Technique

Tocreateajaggedarray,useseparatebracketsforeach

dimensioninthearray.Forinstance,tocreateanarrayofthree

elementswhereeachelementcontainsanotherarrayofa

certainsize,thecodewouldappearasfollows:



int[][]jaggedArrayA=newint[3][];

jaggedArrayA[0]=newint[3];

jaggedArrayA[1]=newint[4];

jaggedArrayA[2]=newint[2];

Intheexample,eachelementinthecreatedarraysisinitialized

to0.Youcanalsoexplicitlyinitializethejaggedarraybyusing

anarrayinitializerlist,asshowninthefollowingexample:



int[][]jaggedArrayB=newint[3][];

jaggedArrayB[0]=newint[]{0,1,2};

jaggedArrayB[1]=newint[]{0,1,2,3,4};

jaggedArrayB[2]=newint[]{0,1};



Comments

Amultidimensionalarrayisarectangulardimensioned

collection.Ifyouweretotakeeachelementandplaceitinrowcolumnformat,theelementswouldformarectanglebecause

eachrowhasthesamenumberofcolumnsasalltheother

rows,assumingatwo-dimensionalstructure,ofcourse.A

jaggedarray,however,cancontainanynumberofelements,

eachofwhichcontainsanarrayofdifferingdimensions.The

termjaggedisusedbecauseplacingthevaluesinarow-column

format,againassumingonlytwodimensionsforsimplicity,

wouldcreateajaggedappearancealongtherightsideofthe

table.Itisbecauseofthischaracteristicthatajaggedarrayis

alsoknownasan"arrayofarrays."



4.3EnumeratingArrayswiththeforeachOperator

Youwanttoaccessalltheelementswithinanarraywithoutrequiring

theuseofindexvalues.



Technique

Toenumerateanarray,usetheforeachiterationstatement,

specifyingthedatatypeofanindividualelementwithinthe

array,thevariablenamefortheelementreturnedasaresultof

theenumeration,andtheinkeywordandvariablenameofthe

array:



staticvoidTestSingleDimensionArray()

{

int[]arr1={1,2,3,4,5,6,7,8,9,10};



foreach(inteleminarr1)

{



Console.WriteLine(elem);

}

}



Comments

Inthepreviousrecipes'codelistings,thecontentsofeacharray

wereenumeratedusingforloops.Forsingle-dimensionarrays,

theformatwassimple.However,assoonasyoubeginadding

extradimensionsinthearray,usingforloopsstartstoseem

lessattractive.Toenumerateamultidimensionarrayusingfor

loops,youhavetocreateaforloopforeachdimensionthatis

nestedwithintheforloopprecedingit.Foranarraywitheven

asmallnumberofdimensions,thisprocesscangetquite

tedious.

Luckily,theC#languagehasabuilt-inenumerationkeyword

designedforthisspecificpurpose.foreachallowsyoutoeasily

accesseverysingleitemwithinacollectioninalinearfashion.

Youcanthereforereplaceeachforloopforamulti-dimension

arraywithasingleforeachstatement.However,whenyoudo

so,youarelosingthebenefitofknowingexactlywhichindexis

beingaccessedwithintheloopbecauseyounolongeruseindex

variablestoaccesseachindividualelement.Forasingledimensionarray,youcansimplycreateanintegervariableand

incrementiteachtimewithinthebodyoftheforeach

statement,butformultidimensionarrays,thisstepisnot

possiblewithoutusinganalgorithmtofigureouttheindexof

thecurrentelementbeingaccessedwithintheforeachloop.

Thenextrecipeshowsonepossiblesolution.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 4. Creating and Using .NET Collections

Tải bản đầy đủ ngay(0 tr)

×