c# - Initializing jagged arrays - Stack Overflow

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

How to create jagged arrays in c#? - Stack Overflow 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 Initializingjaggedarrays AskQuestion Asked 12years,7monthsago Modified 1year,10monthsago Viewed 23ktimes 25 8 Iwanttocreatearray10*10*10inC#likeint[][][](notint[,,]). Icanwritecode: int[][][]count=newint[10][][]; for(inti=0;i<10;i++) { count[i]=newint[10][]; for(intj=0;j<10;j++) count[i][j]=newint[10]; } butIamlookingforamorebeautifulwayforit.Maybesomethinglikethat: int[][][]count=newint[10][10][10]; c#.netjagged-arrays Share Improvethisquestion Follow editedAug14,2020at3:30 AustinWBryan 3,08933goldbadges1818silverbadges3838bronzebadges askedNov15,2009at21:58 AndreyAkinshinAndreyAkinshin 17.8k2929goldbadges9393silverbadges152152bronzebadges Addacomment  |  9Answers 9 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 25 int[][][]my3DArray=CreateJaggedArray(1,2,3); using staticTCreateJaggedArray(paramsint[]lengths) { return(T)InitializeJaggedArray(typeof(T).GetElementType(),0,lengths); } staticobjectInitializeJaggedArray(Typetype,intindex,int[]lengths) { Arrayarray=Array.CreateInstance(type,lengths[index]); TypeelementType=type.GetElementType(); if(elementType!=null) { for(inti=0;i(intcnt,FuncitemCreator){ T[]result=newT[cnt]; for(inti=0;i(10,()=>CreateArray(10,()=>newint[10])); Share Improvethisanswer Follow editedNov15,2009at22:19 answeredNov15,2009at22:13 GuffaGuffa 667k106106goldbadges710710silverbadges988988bronzebadges 0 Addacomment  |  3 WithalittlehelpfromLinq int[][][]count=newint[10][][].Select(t=>newint[10][].Select(tt=>newint[10]).ToArray()).ToArray(); Itsureisn'tprettyandprobablynotfastbutit'saone-liner. Share Improvethisanswer Follow answeredJul19,2018at11:38 BizniztimeBizniztime 1,0061010silverbadges2121bronzebadges Addacomment  |  1 Thereisno'moreelegant'waythanwritingthe2for-loops.Thatiswhytheyarecalled'jagged',thesizesofeachsub-arraycanvary. Butthatleavesthequestion:whynotusethe[,,]version? Share Improvethisanswer Follow answeredNov15,2009at22:14 HenkHoltermanHenkHolterman 252k3030goldbadges307307silverbadges492492bronzebadges 3 7 Multidimensionalarraysareallocatedasonebigblockofmemory,jaggedarraysareseparateblocks-ifthere'slotsofmemoryusage,themultidimensionalarrayismorelikelytocauseOutOfMemoryException.Accessingajaggedarrayisalsofaster(astheCLRisoptimizedforSZarrays-singledimension,zero-based) – thecoop Nov15,2009at22:24 thecoop,youarerightonbothcountsbutneitheramountstomuchaslongassize=10,oreven100.Butbeyondthat,itquicklyaddsup. – HenkHolterman Nov15,2009at22:27 @thecoop,Haveyouactuallytestedwhatyouclaim?I'mcurious. – strager Nov16,2009at2:39 Addacomment  |  1 int[][][]count=Array.ConvertAll(newbool[10],x=> Array.ConvertAll(newbool[10],y=>newint[10])); Share Improvethisanswer Follow editedSep29,2017at23:12 answeredFeb24,2016at23:46 SlaiSlai 21.1k55goldbadges4242silverbadges5050bronzebadges Addacomment  |  0 AthreedimensionalarraysoundslikeagoodcaseforcreatingyourownClass.Beingobjectorientedcanbebeautiful. Share Improvethisanswer Follow answeredNov15,2009at22:00 JamesBrownIsDeadJamesBrownIsDead 11511goldbadge11silverbadge55bronzebadges Addacomment  |  0 Youcoulduseadatasetwithidenticaldatatables.Thatcouldbehavelikea3Dobject(xyz=row,column,table)...Butyou'regoingtoendupwithsomethingbignomatterwhatyoudo;youstillhavetoaccountfor1000items. Share Improvethisanswer Follow answeredNov15,2009at22:04 tsilbtsilb 7,7291313goldbadges6868silverbadges9898bronzebadges Addacomment  |  -1 Whydon'tyoutrythis? int[,,]count=newint[10,10,10];//Multi-dimentionalarray. Anyproblemyouseewiththiskindofrepresentation?? Share Improvethisanswer Follow editedJul4,2019at10:58 answeredJan23,2019at14:56 MaheshBonganiMaheshBongani 61877silverbadges1919bronzebadges 2 That'samultidimensionalarray,notajaggedarray.Seestackoverflow.com/questions/597720/… – Crypth Jun28,2019at8:40 1 Yes,Iknow.Myquestioniswhatistheproblemwithsuchkindofrepresentation. – MaheshBongani Jul4,2019at10:58 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#.netjagged-arraysoraskyourownquestion. TheOverflowBlog Askedandanswered:theresultsforthe2022Developersurveyarehere! LivingontheEdgewithNetlify(Ep.456) FeaturedonMeta Testingnewtrafficmanagementtool AskWizardTestResultsandNextSteps Updatedbuttonstylingforvotearrows:currentlyinA/Btesting Trending:Anewanswersortingoption Linked 495 WhatarethedifferencesbetweenamultidimensionalarrayandanarrayofarraysinC#? 3 Instantiateanarrayofobjects,insimpliestway? 8 Aworkaroundforabigmultidimensionalarray(JaggedArray)C#? 2 Initializedouble[][][]asdouble[1][2][3]usingLINQ 0 multidimensionaljaggedarrayinitialization 1 Initializeandreturnjaggedarrayinoneline Related 2501 Deepcloningobjects 2439 Catchmultipleexceptionsatonce? 3257 Caseinsensitive'Contains(string)' 993 Howwouldyoucountoccurrencesofastring(actuallyachar)withinastring? 2186 GetintvaluefromenuminC# 1911 HowdoIremedy"Thebreakpointwillnotcurrentlybehit.Nosymbolshavebeenloadedforthisdocument."warning? 1802 IsthereareasonforC#'sreuseofthevariableinaforeach? 1602 Try-catchspeedingupmycode? 1311 Howandwhentouse‘async’and‘await’ 1621 WhynotinheritfromList? HotNetworkQuestions Whatdoes"CATsthreeandfour"mean? CanVresolvetoiii? Iboughtmyfirstroadbike,andithurtsmybackandhands /var/loghasreached56.6GB.Howtocleanitandmakemorespace? Doestheemailsizelimitincludethesizeofthebody? Arenutritionvaluesalwaysadditive? ShortofattackingaNATOcountry,isthereanyotherthingRussiacandototriggerdirectAmericanmilitaryconfrontation? Upperboundforrandomcorrelation Isitacceptabletoincludeinformationinaposterthatwasn'tinthepublication? SymmetricalChessPositionWithNoLegalMoves WhyareRoevWadeandPlannedParenthoodvCaseyabbreviatedasRoeandCasey? Isitpracticaltopreventa51%-attackbyhavingasecondminingalgorithm? Additionalresourcesforthistypeofproblemformulation WhatarethemainargumentsusedbyChristianpro-liferstojustifytheirstanceagainstabortion? IsthePharisees'questionontaxationatrickquestionornot? RelationshipbetweentheTQFTsinKapustin-WittenandBen-Zvi-Sakellaridis-Venkatesh Isitcommontoattendtoconferenceofpastpostdocduringanewpostdoc? HowcanIplotasmoothregionbasedondata? Whatisthepointoftermlifeinsurance? WhatisthestrongestmetalintheDCuniverse? ArrayaccessisO(1)impliesafixedindexsize,whichimpliesO(1)arraytraversal? WhatarethecorrectspecsforanSNESpowersupply? Willmymeatloafcookifthesauceismixedintothemeat Doesmycathatemenow morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-cs Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?