A common task during SharePoint's developing is to read from a SharePoint List a item's (SPListItem) value defined in column. It's not a big deal if you information is stored into a text field:
SPList list = SPContext.Current.Web.Lists["List with lookup column"];
foreach (SPListItem item in list.Items)
{
string information = (string)item["YourColum"]
}
This is an easy and fast approch that works well if your column (SPField) is defined as text (SPFieldText), but what happens if you try to read from a different column type, such as from a LookUp Field? What you will get is a rappresentation of that value with this syntax: ID;#TITLE .
Whould it be much better to obtain directly the referenced SPListItem, so you can do whatever you need? Learn how efficently read values from SPFields from this code snippet which is focused to read from lookup fields, but this kind of implementation can be applied on every SPField type:
SPList list = SPContext.Current.Web.Lists["List with lookup column"];
foreach (SPListItem item in list.Items)
{
if (item.Fields["YourLookUpField"] is SPFieldLookup)
{
SPFieldLookup field = (SPFieldLookup)item.Fields[YourLookUpField];
Guid webId = field.LookupWebId;
Guid listId = new Guid(field.LookupList);
int itemId = Int32.Parse(item[YourLookUpField].ToString().Split(';')[0]);
SPListItem lookupItem = null;
// here is you reference...
lookupItem = SPContext.Current.Site.OpenWeb(webId).Lists[listId].GetItemById(itemId);
// do something...for this sample i will get the item's title
string title = lookupItem.Title;
}
}
So remember that when you need to read values from SpListItems, first check your SPField's type, the cast it and then obtain the value you need.