获取某个List里的Lookup字段的值是很普遍的事,那么我们将它封装起来
获取Lookup字段值的方法:
1 /// <summary> 2 /// To get lookup field Id or Value 3 /// </summary> 4 /// <typeparam name="T"></typeparam> 5 /// <param name="item"></param> 6 /// <param name="fieldName"></param> 7 /// <param name="defaultValue"></param> 8 /// <param name="getValueType">0:return Id, 1:return Value</param> 9 /// <returns></returns> 10 public static T GetLookupField<T>(this SPListItem item, string fieldName, int getValueType, T defaultValue) 11 { 12 fieldName = fieldName.Replace(" ", ConstVariables.blankSpicalCode); 13 14 if (item[fieldName] == null) 15 { 16 return defaultValue; 17 } 18 19 var itemElements = Regex.Split(item[fieldName].ToString(), ";#", RegexOptions.IgnoreCase); 20 21 if (itemElements.Length >= 2) 22 { 23 return ConvertTo<T>(itemElements[getValueType], defaultValue); 24 } 25 else 26 { 27 return defaultValue; 28 } 29 }
调用该方法: <oldPlan是SPListItem>
1. 获取Lookup的ID:
oldPlan.GetLookupField<int>(ConstVariables.PRColumns.ColumnStatus, 0, 0);
2. 获取Lookup的Value:
oldPlan.GetLookupField<string>(ConstVariables.AllBGProfileColumns.ColumnBGName, 1, string.Empty)