Code snippet: getting the values of a multi-value lookup field or People and Groups field

I've seen a few ways of getting this done, including regular expressions and other stuff. This is a code snippet of how I do it.

   1: /// <summary>
   2: /// Returns a generic collection of the ID and value of a Lookup-Field with multiple values.
   3: /// </summary>
   4: public static IDictionary<int, string> GetMultiValueLookupFieldItems(this SPListItem item, Guid fieldGuid)
   5: {
   6:     var returnValue = new Dictionary<int,string>();
   7:  
   8:     if (item == null)
   9:         return null;
  10:     
  11:     var lookupField = item.Fields[fieldGuid];
  12:  
  13:     if (lookupField.FieldValueType == typeof(SPFieldLookupValueCollection))
  14:     {
  15:         var lookupFieldValues = item[fieldGuid] as SPFieldLookupValueCollection;
  16:         if (lookupFieldValues == null)
  17:             return null;
  18:         foreach (var value in lookupFieldValues)
  19:         {
  20:             returnValue.Add(value.LookupId, value.LookupValue);
  21:         }
  22:     }
  23:     
  24:     return returnValue;
  25: }

To do this for a People or Group/UserMulti field – the SPFieldUserValueCollection type – just replace SPFieldLookupValueCollection to SPFieldUserValueCollection.

For something really cool, a generic method with casting at runtime would be really cool to accommodate both situations. I'd be interested on that.

Here is how to use the code:

   1: IDictionary<int, string> groups = theSPListItemObject.GetMultiValueLookupFieldItems(c_LookupFieldGuid);

Leave a Reply