Programmatically retrieve all lookup field values

If you are using a lookup field in code and need to retrieve the values available through that lookup, you can do so by writing a generic method to return all possible values in a collection for you to use as needed. Here is an example:

public static List<SPFieldLookupValue> GetLookupFieldValues(SPList list, string fieldName)

    {

        var results = new List<SPFieldLookupValue>();

        var field = list.Fields.GetField(fieldName);

 

        if (field.Type != SPFieldType.Lookup) throw new SPException(String.Format("The field {0} is not a lookup field.", fieldName));

 

        var lookupField = field as SPFieldLookup;

        var lookupList = list.ParentWeb.Lists[Guid.Parse(lookupField.LookupList)];

        var query = new SPQuery();

 

        query.Query = String.Format("<OrderBy><FieldRef Name='{0}'/></OrderBy>", lookupField.LookupField);

 

        foreach (SPListItem item in lookupList.GetItems(query))

        {

            results.Add(new SPFieldLookupValue(item.ID, item[lookupField.LookupField].ToString()));

        }

 

        return results;

    }

Then to use it, your code would look something like this:

var list = SPContext.Current.Web.Lists["My List"];

var results = GetLookupFieldValues(list, "Actual City");

 

foreach (SPFieldLookupValue result in results)

{

    var value = result.LookupValue;

    var id = result.LookupId;

}