When you design a list structure in your SharePoint solution quite often you want to make things easy and configurable and what`s the better way to reference data from other list than using a Lookup field.
Later on when working with the data within your solution, whether it`s an event handler, a workflow or application page – you need to access this data.
If you ever tried to convert SPListItem value that derives from a lookup field to String, you know that you get #`s and other separators. Rather than doing string manipulations – I found it`s better to play it safe and convert the resulting field to it`s original type and access the data from there.
Here is how something like this would look like:
if (item[Constants.MyReferenceField].GetType()== typeof(SPFieldLookupValueCollection))
{
SPFieldLookupValueCollection myReferences = ((SPFieldLookupValueCollection)item[Constants.MyReferenceField]);
if (myReferences != null)
for (int i = 0; i < myReferences.Count; i++)
{
MyReferences.Text = myReferences[i].LookupValue;
}
}
This takes care of verifying that I`m going to convert to the correct type SPFieldLookupValueCollection and then gets a hold of all the values and iterates through their LookupValue. In case you ever wanted to access the ID of the elements that`s being referenced from another list you can access it from the same SPFieldLookupValueCollection – its property is called LookupId.