对ArrayList中的自定义类型进行搜索
一般情况下我只需要使用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(); }