C#配列ソートの2つの一般的な方法
4038 ワード
この例では、C#配列ソートの2つの一般的な方法について説明します.皆さんの参考にしてください.具体的には以下の通りです.
1.第一例
定義コード
テストコード
1.第2例
定義コード
テストコード
本稿で述べたことが皆さんのC#プログラム設計に役立つことを願っています.
1.第一例
定義コード
#region Array 1
public class Pigeon : IComparable
//
{
int XValue;
int YValue;
public string BatchNo { get; set; }
public int CompareTo(Pigeon other)
{
if (other == null)
throw new ArgumentNullException(" ");
//
XValue = Convert.ToInt32(this.BatchNo.Substring(2, 1));
YValue = Convert.ToInt32(other.BatchNo.Substring(2, 1));
if (XValue == YValue)
{
return 0;
}
else if (XValue < YValue)
{
return -1; // -1,X Y
}
else
{
return 1; // 1,X Y
}
}
}
#endregion
テストコード
#region Array 1
private void button3_Click(object sender, EventArgs e)
{
Pigeon[] pigeons = new Pigeon[]{
new Pigeon(){BatchNo="1256"},
new Pigeon(){BatchNo="1236"},
new Pigeon(){BatchNo="1276"},
new Pigeon(){BatchNo="1216"}
};
Array.Sort(pigeons);
string ResultMsg = "";
foreach (Pigeon o in pigeons)
{
ResultMsg += o.BatchNo + "\r
";
}
MessageBox.Show(ResultMsg);
}
#endregion
1.第2例
定義コード
#region Array
public class MyBatch //
{
public string BatchNo { get; set; }
}
public enum CompareType //
{
ThreeChar =0,
FourChar=1
}
public class MyBatchCompare:IComparer
//
{
private CompareType compareType;//
public MyBatchCompare(CompareType compareType)
{
//
this.compareType = compareType;
}
public int Compare(MyBatch x, MyBatch y)
{
int XValue;
int YValue;
if (x == null) throw new ArgumentNullException("x ");
if (y == null) throw new ArgumentNullException("y ");
switch (compareType)
{
case CompareType.ThreeChar:
//
XValue = Convert.ToInt32(x.BatchNo.Substring(2,1));
YValue = Convert.ToInt32(y.BatchNo.Substring(2,1));
if (XValue == YValue)
{
return 0;
}
else if (XValue < YValue)
{
return -1; // -1,X Y
}
else
{
return 1; // 1,X Y
}
case CompareType.FourChar:
//
XValue = Convert.ToInt32(x.BatchNo.Substring(3,1));
YValue = Convert.ToInt32(y.BatchNo.Substring(3,1));
if (XValue == YValue)
{
return 0;
}
else if (XValue < YValue)
{
return -1; // -1,X Y
}
else
{
return 1; // 1,X Y
}
default:
throw new ArgumentException(" ");
}
}
}
#endregion
テストコード
#region Array
private void button2_Click(object sender, EventArgs e)
{
MyBatch[] batchs ={
new MyBatch(){BatchNo="1234"},
new MyBatch(){BatchNo="1263"},
new MyBatch(){BatchNo="1218"},
new MyBatch(){BatchNo="1242"}
};
//
Array.Sort(batchs,new MyBatchCompare(CompareType.ThreeChar));
string ResultMsg = "";
foreach (MyBatch o in batchs)
{
ResultMsg += o.BatchNo + "\r
";
}
MessageBox.Show(ResultMsg);
//
Array.Sort(batchs, new MyBatchCompare(CompareType.FourChar));
ResultMsg = "";
foreach (MyBatch o in batchs)
{
ResultMsg += o.BatchNo + "\r
";
}
MessageBox.Show(ResultMsg);
}
#endregion
本稿で述べたことが皆さんのC#プログラム設計に役立つことを願っています.