I am using SharePoint 2010 and get values from a list using the code below.
It might be called like this: getValueFromList("addresses", "secondName", "city", "manhattan");
It will return the "secondName" of the first entry that has "city = manhattan". Is there a way to make it more efficient?
private string getValueFromList(string theList, string returnColumnName, string matchColumnName, string valueToMatch)
{
try
{
SPSite siteh2 = SPContext.Current.Site;
using (SPWeb oWeb = siteh2.OpenWeb())
{
//SPWeb oWeb = SPControl.GetContextSite(Context).OpenWeb();
SPList oList = oWeb.Lists[theList];
SPQuery oQuery = new SPQuery();
oQuery.Query = "<Where><Eq><FieldRef Name='" + matchColumnName + "' />" +
"<Value Type='Text'>" + valueToMatch + "</Value></Eq></Where>";
//oQuery.Query = "<Query><Where><Eq><FieldRef Name='Username' /><Value Type='Text'>whelanp</Value></Eq></Where></Query>";
SPListItemCollection results = oList.GetItems(oQuery);
if (results.Count == 0)
return "";
foreach (SPListItem oListItem in results)
{
return cleanValue(oListItem[returnColumnName].ToString());
}
return "";
}
}
catch (Exception ex)
{
return "";
}
}