C#陣列Array排序


五一假期回來,練習一下C#的一些知識,了解一下排序。

練習數據:

int[] ints = { 16, 75, 1, 39, 22, 43, 3, 68, 55 };


寫一個類:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplicationDemo
{
    public class Bw
    {
        public int[] ArrayData { get; set; }

        public Bw() { }

        public Bw(int[] myArrayData)
        {
            this.ArrayData = myArrayData;
        }      
    }
}
Source Code

 

為這個類,添加一個方法,arrayToArrayListWithForeach() 即是使用foreach方法,把array數據copy to ArrayList數據集:

 

 System.Collections.ArrayList _al = new System.Collections.ArrayList();

        public void arrayToArrayListWithForeach()
        {
            foreach (int i in ArrayData)
            {
                _al.Add(i);
            }
        }
Source Code

 

把Array數據copy to ArrayList,還可以使用另外的方法,arrayToArrayListWithAddRange()



 public void arrayToArrayListWithAddRange()
        {
            _al.AddRange(ArrayData);
        }
Source Code

 

為上面的類,寫一個ArrayList數據集Sort();

 

public void Sort()
        {
            _al.Sort();
        }
Source Code

 

再為類寫一個方法,就是輸出ArrayList的數據:

 

 public void Output()
        {
            foreach (int i in _al)
            {
                Console.WriteLine(i.ToString());
            }
        }
Source Code

 

所需要的方法,均寫完,在控制台程序使用它們了。

 

 

上面#17,#18行代碼,可以在類new時,一起傳入:

上面#20行代碼,由於我們在Bw這個類別中,有寫了另外一個方法,所以,也可以這樣子:

OK,實現對數據進行排序:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM