C# Array length - Linux Hint

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

If faced with that situation, C# length functions can be an essential to let you know about the exact length of arrays. So, this tutorial will be all about ... Anarrayissaidtobeavariablethatcanholdmultiplevaluesinitoravariablethatisamulti-storagemutablethatcanholdvalueswithoutcreatingnewvariables.Arrayscanbedefinedstaticallybyspecifyingtheirlengthatthetimeofinitializationandcanbedefineddynamicallybynotspecifyinganylength.Theremaycomeasituationwhenyoumustdealwithlargearrays,andyoumayfindyourselfunabletogetthelengthofanarray.Iffacedwiththatsituation,C#lengthfunctionscanbeanessentialtoletyouknowabouttheexactlengthofarrays.So,thistutorialwillbeallaboutthosefunctionstogetthelengthsofanarray.Let’smakeourarticlestartwiththeupdateofourLinuxsystemi.e.Ubuntu20.04.Forthis,startyourshellapplication.Wehavebeenutilizingtheaptpackageinthe“update”instructionforthispurpose.Thesystemwillgetuptodateinnomorethan15seconds. Now,it’stimetocreateaC#fileinwhichwehavetocreatesome.Netcode.Thisfilemustbesavedinthehomedirectory.Therefore,wehavebeenutilizingthecurrenthomelocatedintheterminalandcreatingitwiththe“touch”instruction.Wehavenamedit“length.cs”.Onlistingthehomefoldercontentswiththelistcommand,wehavegotthenewlycreatedfileaswell. Example01: Inthefirstexample,wewilllookatgettingthelengthofastringtypearray.YouneedtoopenthisnewlycreatedfileinanyoftheLinuxeditors.Forconvenience,weusedthesimpletexteditor(i.e.insert,update,saveandexit.)WehavebeenstartingourfirstexamplewiththeC#main“System”librarywhichisamustineachC#codetomakeitworkproperly. Wehavebeenusingthekeyword“using”tousetheSystemlibrary.Afterthis,wehavebeenstartingauser-defined“Test”classwiththekeyword“class”followedbythebrackets.Everythingwillbeperformedwithinthisclass.EveryprograminC#isexecutedusingthemain()functionofC#.So,wehavestartedthestaticvoidmain()functionbyinitializingastringarraynamed“Arr”andassigningitsomestringvalues.Herecomesthe“foreach”looptoiteratethevaluesofastringarray“Arr”.Eachvalue“val”inarray“Arr”willbeprintedoutontheshellfollowedbyaspaceusingthe“Write”functionofC#’sConsoleclass.TheConsoleclassisthemostusedgenericclassofC#thatispurposelydesignedtoholdread,andwritefunctions. TheverynextWrite()functionoftheConsoleclasshasbeenusedtogivealinebreakanddisplay“LengthofArr”ontheshell.ThenextWrite()functionfortheConsoleclassisusedtogetanddisplaythelengthofanarray“Arr”callingthe“Length”functionoftheConsoleclasswiththe“dot”product.ThelastWrite()functionhasbeenaddingalinebreakagain.Wehaveclosedthemain()functionandTestclassattheend.SavedthecodewithCtrl+S. Nowthecodeisreadytobeusedontheshell.Wehaveusedthe“mcs”compilerfor“C#”intheUbuntushelltocompilethefile“length.cs”inaninstant.Thelength.exefilegotcreatedandwehaveusedthemono-runtimetoexecutethisexecutablefileontheshell.Thearray“Arr”gotdisplayedonthefirstlineandthetotallengthofthisarrayhasbeendisplayedonthenextlinei.e.5. Example02: WehavecoveredthefirstexamplewiththeuseoftheLength()functionfromtheConsoleclasstogetthelengthofastringtypearray.It’stimetogetthelengthforsomeinteger-typearraysinC#.WehavestartedthisexamplewiththesameSystemlibraryanduser-defined“Test”class.Withinthestaticvoidmain()function,wehaveinitialized2arraysofintegertype.ThefirstarrayA1is2-dimensionalwhilethearrayA2is3-dimensional. Accordingtoourinformation,theLengthfunctionmustworkonboththearraysameasitworksonanysimpleand1-dimensionalarraywithoutanyproblem.Theresultis,thefirsttwoWrite()functionsoftheConsoleclasshavebeenusedtodisplaythelengthofthe2-dimensionalarray“A1”usingthe“Length”functionbycallingitwithin.The3rdand4thWrite()functionfortheConsoleclassisusedtodisplaythelengthof3-dimensionalarrayA2ontheshellwiththehelpofa“Length”functionforC#.ThelastWritefunctionhasbeenusedtogivealinebreakusingthe“\n”characterwiththeConsoleclass.Themain()programandtheclassTesthavebeencompletedandclosedherewithbrackets.Savethiscodeandexitthefiletorunitontheshell. Wehavebeenusingthe“mcs”compilerforC#againontheshelltocompileourlength.csfile.Itcreatedalength.exeexecutablefileinthehomefolder.Wehaveusedthemono-runtimecommandtoexecuteourexecutablefileforC#andgotthebelow-shownoutput.ItdisplayedthelengthofA1as10andlengthofA2as12i.e.lengthisequaltothetotalitemsinanarray. Example03: BoththeaboveexampleswereusingtheConsoleclass“Length()”functiontogetthearraylengthforsomedifferentdimensionalintegerarraysandstringarrays.Now,wewillbelookingatanotherfunctioni.e.“Count”functiontogetthelengthofarrays.Tousethe“Count”function,wehavebeenusingthe“Linq”namespaceoftheSystemlibrarythatholdstheEnumerableclass.ThisEnumerableclasscontainsthe“Count”functioninit. Useofthe“System”libraryisamust.TheTestclassandmain()functionhasbeenstarted.AnemptyarrayA1ofsize10hasbeendefinedandCount()functionisusingittogetthelength.Theresultwillbesavedtovariablev1andtheWriteLine()functionoftheConsoleclasswillbeusedtodisplayitontheshell.ThenwehaveinitializedanotherarrayA2withsomeintegervaluesandusedtheCount()functiontofinditslengthorthetotalnumberofelements.Theresultwillbesavedtovariablev2andtheWriteLine()functionoftheConsoleclasswilldisplayitontheshellscreen. Oncompilingthelength.csfileandrunningthelength.exefileontheshell,wehavegotthelengthofbotharraysi.e.10and12respectively. Conclusion: Thisarticle’sintroductionexplainsthedefinitionanduseofarraysindifferentprogramminglanguagesandthetypesofarrayswecanmakei.e.dynamicvsstatic.Thefirst2exampleselegantlydemonstratestheuseoftheLength()functionfortheConsoleclasstofindoutthelengthforstringarrays,2-dimensional,and3-dimensionalintegerarrays.ThelastexampleisutilizedtodemonstratetheuseoftheCount()functionfortheLinqnamespaceofC#todothesametask.Boththefunctionsdothesameworkandonecanusethemalternatively. Abouttheauthor AqsaYasin Iamaself-motivatedinformationtechnologyprofessionalwithapassionforwriting.IamatechnicalwriterandlovetowriteforallLinuxflavorsandWindows. Viewallposts RELATEDLINUXHINTPOSTS C#RenameFileC#StringReplaceC#InternalC#OpenFileC#OperatorOverloadingC#ProgressBarC#RemoveDuplicatesFromaList



請為這篇文章評分?