排序方式(枚举)
1 public enum SortBy 2 { 3 Asc, 4 Desc 5 }
数组冒泡排序方法
1 public class SortEntity 2 { 3 public static int[] SortArray(int[] array,SortBy sortby) 4 { 5 int flag; 6 switch (sortby) 7 { 8 case SortBy.Asc: 9 for (int i = 0; i < array.Length - 1; i++) 10 { 11 for (int j = 0; j < array.Length - 1 - i; j++) 12 { 13 if (array[j] < array[j + 1]) 14 { 15 flag = array[j]; 16 array[j] = array[j + 1]; 17 array[j + 1] = flag; 18 } 19 } 20 } 21 break; 22 case SortBy.Desc: 23 for (int i = 0; i < array.Length - 1; i++) 24 { 25 for (int j = 0; j < array.Length - 1 - i; j++) 26 { 27 if (array[j] > array[j + 1]) 28 { 29 flag = array[j]; 30 array[j] = array[j + 1]; 31 array[j + 1] = flag; 32 } 33 } 34 } 35 break; 36 default: 37 break; 38 } 39 40 return array; 41 } 42 }
String类型的int数组转换成int数组
1 public class ArrayHelper 2 { 3 public static int[] GetIntArrayFromString(string StringStr) 4 { 5 string[] array = StringStr.Split(‘,‘); 6 int Flag; int[] ArrayIntNum = new int[array.Length]; 7 for (int i = 0; i < array.Length - 1; i++) 8 { 9 if (int.TryParse(array[i], out Flag)) 10 { 11 ArrayIntNum[i] = Flag; 12 } 13 else 14 { 15 throw new Exception("内容中含有非int型数据"); 16 } 17 } 18 return ArrayIntNum; 19 } 20 }
文件读取数组
1 public class FileEntity 2 { 3 public string address { get; set; } 4 private string ReadContent() 5 { 6 string Content = string.Empty; 7 if (File.Exists(this.address)) 8 { 9 Content = File.ReadAllText(this.address); 10 11 } 12 return Content; 13 } 14 public int[] GetArray() 15 { 16 return ArrayHelper.GetIntArrayFromString(ReadContent()); 17 } 18 }
测试方法
1 public void Test() 2 { 3 int[] intArray = new int[] { 1, 2, 3, 4, 5 }; 4 int[] txtArray = new FileEntity() { address = @"C:\TEST.TXT" }.GetArray(); 5 int[] dataArray = new DataBaseEntity().GetArray(); 6 intArray = SortEntity.SortArray(intArray, SortBy.Asc); 7 txtArray = SortEntity.SortArray(txtArray, SortBy.Asc); 8 dataArray = SortEntity.SortArray(dataArray, SortBy.Asc); 9 }
时间: 2024-10-26 22:22:51