Array Size (Length) in C# - Stack Overflow
文章推薦指數: 80 %
If it's a one-dimensional array a , a.Length. will give the number of elements of a . If b is a rectangular multi-dimensional array (for ...
Resultsfromthe2022DeveloperSurveyarenowavailable
Home
Public
Questions
Tags
Users
Companies
Collectives
ExploreCollectives
Teams
StackOverflowforTeams
–Startcollaboratingandsharingorganizationalknowledge.
CreateafreeTeam
WhyTeams?
Teams
CreatefreeTeam
Collectives™onStackOverflow
Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost.
Learnmore
Teams
Q&Aforwork
Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch.
Learnmore
ArraySize(Length)inC#
AskQuestion
Asked
12years,1monthago
Modified
2years,2monthsago
Viewed
316ktimes
116
16
HowcanIdeterminesizeofanarray(length/numberofitems)inC#?
c#arrayssize
Share
Improvethisquestion
Follow
editedFeb23,2019at12:34
Toastrackenigma
6,32944goldbadges3939silverbadges5252bronzebadges
askedMay16,2010at13:49
AmalAmal
1,37533goldbadges99silverbadges88bronzebadges
4
1
@Marcelo:...butitstillcan'tanswerreallysimplequestionslike"Wherearemyglasses".;)
– Guffa
May16,2010at13:55
2
Whatdoyoumeanwith"size"?Thenumberofelementsorsizeinbytes?
– FredrikMörk
May16,2010at14:11
2
@fearofawhackplanetIupvotedbecauseIhadthesameproblemoffindingLengthdidn'tworkformulti-dimensionalarraysandasaresultofthisquestiondiscoveringRankandGetLength(index).
– TheMathemagician
Aug21,2015at10:20
1
@fearofawhackplanetIbelievethefactthatithas145,000viewsisatestamenttoitsrelevance.Upvoted.
– brycejl
Mar6,2018at21:23
Addacomment
|
9Answers
9
Sortedby:
Resettodefault
Highestscore(default)
Trending(recentvotescountmore)
Datemodified(newestfirst)
Datecreated(oldestfirst)
165
Ifit'saone-dimensionalarraya,
a.Length
willgivethenumberofelementsofa.
Ifbisarectangularmulti-dimensionalarray(forexample,int[,]b=newint[3,5];)
b.Rank
willgivethenumberofdimensions(2)and
b.GetLength(dimensionIndex)
willgetthelengthofanygivendimension(0-basedindexingforthedimensions-sob.GetLength(0)is3andb.GetLength(1)is5).
SeeSystem.Arraydocumentationformoreinfo.
As@Luceropointsoutinthecomments,thereisaconceptofa"jaggedarray",whichisreallynothingmorethanasingle-dimensionalarrayof(typicallysingle-dimensional)arrays.
Forexample,onecouldhavethefollowing:
int[][]c=newint[3][];
c[0]=newint[]{1,2,3};
c[1]=newint[]{3,14};
c[2]=newint[]{1,1,2,3,5,8,13};
Notethatthe3membersofcallhavedifferentlengths.
Inthiscase,asbeforec.Lengthwillindicatethenumberofelementsofc,(3)andc[0].Length,c[1].Length,andc[2].Lengthwillbe3,2,and7,respectively.
Share
Improvethisanswer
Follow
editedDec22,2014at16:06
answeredMay16,2010at13:51
BlairConradBlairConrad
220k2525goldbadges129129silverbadges110110bronzebadges
4
1
Forcompletenessyoucouldalsohavelistedthewayjaggedarrayswork(e.g.int[][]);-)
– Lucero
May16,2010at14:00
Iconsideredit,@Lucerno,butfigureditadifferentproblem-figuringoutthesizeofthingsinsideanarray-ajaggedarray'sreallyjustasingle-dimensionedarraythathappenstocontainsingled-dimensionedarrays,asI'msureyouknow.
– BlairConrad
May16,2010at16:04
4
ofcourseIknowthatyou'rerightandthat'swhyIaddedthecommentwithasmileyinsteadofwritingananswermyself.However,thedistinctionbetween[,]and[][]doesn'tseemtobeclearforall.NETnewbies,soitmaystillbeworthnotingthat[][]isnotamultidimensionalarrayinyouranswerssense.
– Lucero
May16,2010at16:08
2
Goodanswer.But,youmightwanttochangeb.GetLength[0]is3andb.GetLength[1]is5shouldbeb.GetLength(0)andb.GetLength(1).
– yurisich
Mar28,2012at13:41
Addacomment
|
32
YoucanlookatthedocumentationforArraytofindouttheanswertothisquestion.
InthisparticularcaseyouprobablyneedLength:
intsizeOfArray=array.Length;
Butsincethisissuchabasicquestionandyounodoubthavemanymorelikethis,ratherthanjusttellingyoutheanswerI'drathertellyouhowtofindtheansweryourself.
VisualStudioIntellisense
Whenyoutypethenameofavariableandpressthe.keyitshowsyoualistofallthemethods,properties,events,etc.availableonthatobject.Whenyouhighlightamemberitgivesyouabriefdescriptionofwhatitdoes.
PressF1
Ifyoufindamethodorpropertythatmightdowhatyouwantbutyou'renotsure,youcanmovethecursoroveritandpressF1togethelp.Hereyougetamuchmoredetaileddescriptionpluslinkstorelatedinformation.
Search
ThesearchtermssizeofarrayinC#givesmanylinksthattellsyoutheanswertoyourquestionandmuchmore.Oneofthemostimportantskillsaprogrammermustlearnishowtofindinformation.Itisoftenfastertofindtheansweryourself,especiallyifthesamequestionhasbeenaskedbefore.
Useatutorial
IfyouarejustbeginningtolearnC#youwillfinditeasiertofollowatutorial.IcanrecommendtheC#tutorialsonMSDN.Ifyouwantabook,I'drecommendEssentialC#.
StackOverflow
Ifyou'renotabletofindtheansweronyourown,pleasefeelfreetopostthequestiononStackOverflow.Butweappreciateitifyoushowthatyouhavetakentheefforttofindtheansweryourselffirst.
Share
Improvethisanswer
Follow
editedMay16,2010at14:30
answeredMay16,2010at13:52
MarkByersMarkByers
770k176176goldbadges15431543silverbadges14341434bronzebadges
6
3
Goodjob,Mark,butmaybeanoverkill!
– Nayan
May16,2010at14:35
2
@Nayan:Thanks!Whileit'sgreatthattheOPgothisanswerfastfromotherposters,Ifeelit'smoreimportanttoteachbeginnershowtofindinformationratherthanteachingthemanswerstospecificquestions.IhopetheOPfindsthisanswerusefulandthatitsavesthemhavingtoaskhundredsofquestionsthattheycouldhavefoundtheanswerstothemselves.
– MarkByers
May16,2010at14:37
13
+1fortakingthetimetotakethisapproach-"giveamanafish..."etc.
– PeterKelly
May16,2010at15:34
IfIeverhavetodothesame,I'lljustredirecttheOPstoyouranswerhere=)Andyes,Icompletelyagreewithyou!
– Nayan
May17,2010at19:57
1
ThisisgoodbutIfeelitshouldbelinkedtoautomaticallysomehow.Can'ttheystarta"answersworthviewing"page?OnethingthatIwouldaddthoughisthatoneshouldcheckstackoverflowitselfbeforepostingthequestion.OftentimesIjuststartpostingthequestionandthenseetherelatedquestionsthatpopup.Iamnotsureiftheanswerexistselsewhereontheinternetifitdoesn'tbelongheretoo.
– user420667
Nov18,2011at21:26
|
Show1morecomment
20
for1dimensionalarray
int[]listItems=newint[]{2,4,8};
intlength=listItems.Length;
formultidimensionalarray
intlength=listItems.Rank;
Togetthesizeof1dimension
intlength=listItems.GetLength(0);
Share
Improvethisanswer
Follow
editedAug22,2017at0:39
gnivler
10011silverbadge1313bronzebadges
answeredMay16,2010at15:54
JohnnyJohnny
1,55533goldbadges1414silverbadges2323bronzebadges
2
2
TheRankpropertydoesn'treturnthenumberofitems,itreturnsthenumberofdimensions.
– Guffa
Apr6,2012at17:05
WherecanIfinddocumentationforthepropertiessupportedby1dimensionalarrays?(i.e.,Length,Rank,GetLength)
– MinhTran
Sep15,2018at16:16
Addacomment
|
11
yourArray.Length:)
Share
Improvethisanswer
Follow
answeredMay16,2010at13:51
PetarMinchevPetarMinchev
46k1111goldbadges102102silverbadges118118bronzebadges
Addacomment
|
8
WiththeLengthproperty.
int[]foo=newint[10];
intn=foo.Length;//n==10
Share
Improvethisanswer
Follow
answeredMay16,2010at13:51
JorenJoren
14.1k33goldbadges4949silverbadges5353bronzebadges
0
Addacomment
|
5
Forasingledimensionarray,youusetheLengthproperty:
intsize=theArray.Length;
FormultipledimensionarraystheLengthpropertyreturnsthetotalnumberofitemsinthearray.YoucanusetheGetLengthmethodtogetthesizeofoneofthedimensions:
intsize0=theArray.GetLength(0);
Share
Improvethisanswer
Follow
answeredMay16,2010at13:53
GuffaGuffa
667k106106goldbadges710710silverbadges988988bronzebadges
Addacomment
|
4
Inmostofthegeneralcases'Length'and'Count'areused.
Array:
int[]myArray=newint[size];
intnoOfElements=myArray.Length;
TypedListArray:
List
延伸文章資訊
- 1在C# 中獲取陣列的大小 - Delft Stack
有兩種主要方法可用於獲取C# 中的陣列大小,Array.Length 屬性和Array.Rank 屬性。
- 2How to find the length of an Array in C# - GeeksforGeeks
Array.Length Property is used to get the total number of elements in all the dimensions of the Ar...
- 3Array Class (System) | Microsoft Docs
- 4Array.Length 屬性(System) | Microsoft Docs
它也會使用GetUpperBound 方法來判斷多維度陣列中每個維度中的專案數目。 C# 複製. 執行.
- 5Calculate length of array in C – 2 Code Examples - Interview Sansar