一般情況下我只需要使用ArrayList.Contains()方法就可以判斷某個元素是否存在,但如果ArrayList中的為自定義的類就需要自己實現,如下面例子:
如我們有一個類:
public class Employee { public int EmployeeID { get;set; } public string EmployeeName { get;set; } public DateTime BirthDate { get; set; }
}
我們要實現對ArrayList中存儲的Employee 進行查找。先定義兩個枚舉:
public enum MemType { IntegerType = 1, StringType = 2, DateTimeType = 3, BooleanType = 4 }; public enum CmpOperator { GreaterThan = 1, LessThan = 2, EqualTo = 3 }
下面是具體實現:
public static int Search(ArrayList objArr, string valueToSearch, string FieldName, MemType memType, CmpOperator comOp) { if (memType == MemType.StringType || memType == MemType.BooleanType) { comOp = CmpOperator.EqualTo; } for (int i = 0; i < objArr.Count; i++) { Type t = objArr[0].GetType(); System.Reflection.FieldInfo[] arrInner = t.GetFields(); System.Reflection.PropertyInfo PI = t.GetProperty(FieldName); string str = PI.GetValue(objArr[i], null).ToString(); switch (memType) { case MemType.BooleanType: if (Convert.ToBoolean(str) == Convert.ToBoolean(valueToSearch)) { return i; } break; case MemType.DateTimeType: switch (comOp) { case CmpOperator.EqualTo: if (Convert.ToDateTime(str).CompareTo(Convert.ToDateTime(valueToSearch)) == 0) { return i; } break; case CmpOperator.GreaterThan: if (Convert.ToDateTime(str).CompareTo(Convert.ToDateTime(valueToSearch)) > 0) { return i; } break; case CmpOperator.LessThan: if (Convert.ToDateTime(str).CompareTo(Convert.ToDateTime(valueToSearch)) < 0) { return i; } break; } break; case MemType.IntegerType: switch (comOp) { case CmpOperator.EqualTo: if (Convert.ToInt32(str) == Convert.ToInt32(valueToSearch)) { return i; } break; case CmpOperator.GreaterThan: if (Convert.ToInt32(str) > Convert.ToInt32(valueToSearch)) { return i; } break; case CmpOperator.LessThan: if (Convert.ToInt32(str) < Convert.ToInt32(valueToSearch)) { return i; } break; } break; case MemType.StringType: if (str.Contains(valueToSearch)) { return i; } break; } } return -1; }
測試代碼如下:
static void Main(string[] args) { ArrayList al = new ArrayList(); Employee emp1 = new Employee(); emp1.EmployeeID = 2; emp1.EmployeeName = "cary"; emp1.BirthDate = new DateTime(1982, 4, 1); Employee emp2 = new Employee(); emp2.EmployeeID = 3; emp2.EmployeeName = "james"; emp2.BirthDate = new DateTime(1983, 4, 1); al.Add(emp1); al.Add(emp2); int searIndex = Search(al, "3", "EmployeeID", MemType.IntegerType, CmpOperator.EqualTo); Console.WriteLine(searIndex); Console.ReadLine(); }