- usingSystem;
- usingSystem.Collections;
- publicclassSamplesArrayList{
- publicstaticvoidMain(){
- //CreatesandinitializesthesourceArrayList.
- ArrayListmySourceList=newArrayList();
- mySourceList.Add("three");
- mySourceList.Add("napping");
- mySourceList.Add("cats");
- mySourceList.Add("in");
- mySourceList.Add("the");
- mySourceList.Add("barn");
- //Createsandinitializestheone-dimensionaltargetArray.
- String[]myTargetArray=newString[15];
- myTargetArray[0]="The";
- myTargetArray[1]="quick";
- myTargetArray[2]="brown";
- myTargetArray[3]="fox";
- myTargetArray[4]="jumped";
- myTargetArray[5]="over";
- myTargetArray[6]="the";
- myTargetArray[7]="lazy";
- myTargetArray[8]="dog";
- //DisplaysthevaluesofthetargetArray.
- Console.WriteLine("ThetargetArraycontainsthefollowing(beforeandaftercopying):");
- PrintValues(myTargetArray,'');
- //CopiesthesecondelementfromthesourceArrayListtothetargetArray,startingatindex7.
- mySourceList.CopyTo(1,myTargetArray,7,1);
- //DisplaysthevaluesofthetargetArray.
- PrintValues(myTargetArray,'');
- //CopiestheentiresourceArrayListtothetargetArray,startingatindex6.
- mySourceList.CopyTo(myTargetArray,6);
- //DisplaysthevaluesofthetargetArray.
- PrintValues(myTargetArray,'');
- //CopiestheentiresourceArrayListtothetargetArray,startingatindex0.
- mySourceList.CopyTo(myTargetArray);
- //DisplaysthevaluesofthetargetArray.
- PrintValues(myTargetArray,'');
- }
- publicstaticvoidPrintValues(String[]myArr,charmySeparator){
- for(inti=0;i<myArr.Length;i++)
- Console.Write("{0}{1}",mySeparator,myArr[i]);
- Console.WriteLine();
- }
- }
- /*
- Thiscodeproducesthefollowingoutput.
- ThetargetArraycontainsthefollowing(beforeandaftercopying):
- Thequickbrownfoxjumpedoverthelazydog
- Thequickbrownfoxjumpedoverthenappingdog
- Thequickbrownfoxjumpedoverthreenappingcatsinthebarn
- threenappingcatsinthebarnthreenappingcatsinthebarn
- */
还记得当初我刚出去面试的时候,一个经典的小算法题目,我是用的最菜鸟最原始的方式,以下是我写的代码
- usingSystem.Collections;
- namespace面试题目
- {
- class数组操作
- {
- privatestringname;
- ///<summary>
- ///产生一个int数组,长度为100,并向其中随机插入1-100,并且不能重复。
- ///</summary>
- publicvoidinsertArr()
- {
- //定义一个长度为100的数组
- int[]arr=newint[100];
- //定义动态数组--方便储值
- ArrayListlist=newArrayList();
- Randomran=newRandom();
- //当动态数组个数不满100时,循环生成随机数
- while(list.Count<100)
- {
- intnum=ran.Next(1,101);
- //如果产生的随机数不包含在动态数组list中(不重复),就添加进list
- if(!list.Contains(num))
- {
- list.Add(num);
- }
- }
- //通过循环,将动态数组list中的元素复制给数组arr
- for(inti=0;i<100;i++)
- {
- arr[i]=(int)list[i];
- }
- }
- }
- }