//例子 返回集合中字段名为ID,值为001的对象所在序号; int num = SearchListByT<string,People>(AppData.TotalPeople,"ID","001"); #region 通过字段名和变量值获取集合序号 /// <summary> /// 获取类中的属性值 /// </summary> /// <param name="FieldName"></param> /// <param name="obj"></param> /// <returns></returns> private static T GetModelValue<T>(string FieldName, object obj) { try { Type Ts = obj.GetType(); T o = (T)Ts.GetProperty(FieldName).GetValue(obj); if (string.IsNullOrEmpty(o.ToString())) return default(T); return o; } catch { return default(T); } } /// <summary> /// 设置类中的属性值 /// </summary> /// <param name="FieldName"></param> /// <param name="obj"></param> /// <returns></returns> private static bool SetModelValue<T>(string FieldName, T Value, object obj) { try { Type Ts = obj.GetType(); object v = Convert.ChangeType(Value, Ts.GetProperty(FieldName).PropertyType); Ts.GetProperty(FieldName).SetValue(obj, v, null); return true; } catch { return false; } } /// <summary> /// 遍历Object集合,获取字段名和值相同的集合的序号 /// </summary> /// <param name="list">遍历的集合</param> /// <param name="FieldName">字段名</param> /// <param name="value">字段数据</param> /// <typeparam name="T">字段类型</typeparam> /// <returns></returns> public static int SearchListByT<T,U>(System.Collections.Generic.List<U> list, string FieldName, T value) { for (int i = 0; i < list.Count; ++i) { T re = GetModelValue<T>(FieldName, list[i]); if (value.Equals(re)) { return i; } } return -1; } #endregion