Array Size (Length) in C# - Stack Overflow

文章推薦指數: 80 %
投票人數:10人

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: ListmyArray=newList(); intnoOfElements=myArray.Count; Share Improvethisanswer Follow answeredApr25,2013at5:06 KbManuKbManu 41033silverbadges77bronzebadges Addacomment  |  1 itgoeslikethis: 1D: type[]name=newtype[size]//or=newtype[]{.....elements...} 2D: type[][]name=newtype[size][]//secondbracketsareemtpy thenasyouusethisarray: name[i]=newtype[size_of_sec.Dim] orYoucandeclaresomethinglikeamatrix type[,]name=newtype[size1,size2] Share Improvethisanswer Follow answeredMay16,2010at16:34 SaraSte.SaraSte. 1322bronzebadges Addacomment  |  1 WhathasbeenmissedsofariswhatIsuddenlywasirritatedabout: HowdoIknowtheamountofitemsinsidethearray?Is.Lengthequal.CountofaList? Theansweris:theamountofitemsoftypeXwhichhavebeenputintoanarrayoftypeXcreatedwithnewX[number]youhavetocarryyourself! Eg.usingacounter:intcountItemsInArray=0andcountItemsInArray++foreveryassignmenttoyourarray. (ThearrayjustcreatedwithnewX[number]hasallspacefornumberitems(references)oftypeXalreadyallocated,youcanassigntoanyplaceinsideasyourfirstassignment,forexample(ifnumber=100andthevariablename=a)a[50]=newX();. Idon'tknowwhetherC#specifiestheinitialvalueofeachplaceinsideanarrayuponcreation,ifitdoesn'tortheinitialvalueyoucannotcompareto(becauseitmightbeavalueyouyourselfhaveputintothearray),youwouldhavetotrackwhichplacesinsidethearrayyoualreadyassignedtotooifyoudon'tassignsequentiallystartingfrom0(inwhichcaseallplacessmallerthancountItemsInArraywouldbeassignedto).) Inyourquestionsizeofanarray(length/numberofitems)dependingonwhether/ismeanttostandfor"alternative"or"divideby"thelatterstillhastobecovered(the"numberofitems"Ijustgaveas"amountofitems"andothersgave.Lengthwhichcorrespondstothevalueofnumberinmycodeabove): C#hasasizeofoperator(https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/sizeof).It'ssafetouseforbuilt-intypes(suchasint)(andonlyoperatesontypes(notvariables)).Thusthesizeofanarrayboftypeintinbyteswouldbeb.Length*sizeof(int). (Duetoallspaceofanarrayalreadybeingallocatedoncreation,likementionedabove,andsizeofonlyworkingontypes,nocodelikesizeof(variable)/sizeof(type)wouldworkoryieldtheamountofitemswithouttracking.) Share Improvethisanswer Follow answeredApr25,2020at23:23 user5588495user5588495 5111silverbadge44bronzebadges Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedc#arrayssizeoraskyourownquestion. TheOverflowBlog Askedandanswered:theresultsforthe2022Developersurveyarehere! LivingontheEdgewithNetlify(Ep.456) FeaturedonMeta Testingnewtrafficmanagementtool AskWizardTestResultsandNextSteps Updatedbuttonstylingforvotearrows:currentlyinA/Btesting Trending:Anewanswersortingoption Linked 2 HowcanIcountthenumberofelementsinanarray? -1 IndexOutOfRangeExceptionC#Multi-DimensionalArray -3 ConvertingJavalooptoC# 0 FindcompressedtotalZipFilesizeinKB(notlength) 0 Howtouseasizeofwithanintegerarraytoavoid"Arraydoesnothaveapredefinedsize[...]isavariableandusedlikeatype" -1 Howtogetthenumberofentriestoanarraytocomparewithanint? -1 HowtoknowifindexofsplittingastringexistC#.NET Related 1277 HowdoIdeterminethesizeofmyarrayinC? 2891 Howtoappendsomethingtoanarray? 3724 CheckingifakeyexistsinaJavaScriptobject? 3695 Sortarrayofobjectsbystringpropertyvalue 2388 HowdoIdeclareandinitializeanarrayinJava? 2384 GetalluniquevaluesinaJavaScriptarray(removeduplicates) 3741 LoopthroughanarrayinJavaScript 10696 HowcanIremoveaspecificitemfromanarray? 2023 Copyarraybyvalue 5383 For-eachoveranarrayinJavaScript HotNetworkQuestions Uglyshadowglitch Satyricon136.7-8 Whycan'tItakephotosinsideofstoresinPortugal? Dosymmetricalairfoilsgenerateinduceddrag? Whatisthepurposeofindexingthemempoolbythesefivecriteria? IsthePharisees'questionontaxationatrickquestionornot? Children'sscifibookfrom'90s/early2000sthathadacoverwithtwokids,andaringedplanetinthebackground Whatisthepointoftermlifeinsurance? What'smakingthescenariocontradictorytoMaxwell'stheoryofemwaves? ShortofattackingaNATOcountry,isthereanyotherthingRussiacandototriggerdirectAmericanmilitaryconfrontation? Hypothetically,canearlyhumansdomesticategiantantssimilartowolves?Maybeevenassistthemintheagriculturalrevolution? DidJuliusCaesarreducethenumberofslaves? Canthepatentandpaperhavedifferentauthors(assumetheyincludethesamecontent)? CantheEnormousTentaclesee? Whatdoes"CATsthreeandfour"mean? Howtallarethemushrooms? CanPostgreSQLuseindexestoexpeditecount(distinct)queries? Whyarejudicialcircuitssonamed? Drawboxesaroundnodesintikz Arenutritionvaluesalwaysadditive? SciFiinvolvingportalstodistantworldsthatleavepeoplestrandedfarfromearth SymmetricalChessPositionWithNoLegalMoves Howtoreplaceantidiagonalelementsofamatrix Is"¿Quédicessiterompolacara?"agoodtranslationof"what'dyousayaboutmebreakingyourface"? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-cs Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?