C# Array length - Linux Hint
文章推薦指數: 80 %
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
延伸文章資訊
- 1How to count elements in C# array? - TutorialsTeacher
How to count elements in C# array? ... You can count the total number of elements or some specifi...
- 2How to get the length of a multidimensional array in C# ...
To get the length of a multidimensional (row/column) array, we can use the Array.GetLength() meth...
- 3在C# 中獲取陣列的大小 - Delft Stack
有兩種主要方法可用於獲取C# 中的陣列大小,Array.Length 屬性和Array.Rank 屬性。
- 4C# Array.Length屬性代碼示例- 純淨天空
C# Array.Length屬性代碼示例,System.Array.Length用法.
- 5Array.Length 屬性(System) | Microsoft Docs
它也會使用GetUpperBound 方法來判斷多維度陣列中每個維度中的專案數目。 C# 複製. 執行.