HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Get a value from a list in Sharepoint 2010

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sharepointvaluegetlistfrom2010

Problem

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 = "" +
                "" + valueToMatch + "";

            //oQuery.Query = "whelanp";

            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 "";
    }
}

Solution

Naming conventions:

As per the Microsoft guidelines, use PascalCase for method names. Read more here: Capitalization Conventions. Your method names will become GetValueFromList and CleanValue.

Object Initialization and Format String:

Use the String.Format method to build your string, don't use concatenation. The building of your CAML query will be:

var spQuery = new SPQuery
{
    Query = String.Format("{1}", matchColumnName , valueToMatch)
};


More reading on Object and Collection Initializers.

Get SharePoint list:

Don't blindly use web.Lists["listName"], it depends on the number of lists you have in your environment what call you should use.

Using web.Lists["listName"], SharePoint will look for all lists in the current web-object and fetch all metadata from them. Then it compares the name you provided and return the correct list.

And SPWeb.GetList("url/to/list") will make a call to the DB for each list for which info is needed.

If you have a lot of lists (thousands), use the second method, otherwise the first will normally score better. Also, this depends on the performance of your hardware. But in general, I tend to avoid the indexer (using the second method or even web.TryGetList("listTitle")).

The foreach loop:

You have this piece of code:

foreach (SPListItem oListItem in results)
{
    return cleanValue(oListItem[returnColumnName].ToString());
}


Why have a loop if you will return on the first item? If you only want to return the first entry, use the SPQuery.RowLimit property and set it to 1:

var spQuery = new SPQuery
{
    Query = String.Format("{1}", matchColumnName , valueToMatch),
    RowLimit = 1
};


Following code:

SPListItemCollection results = oList.GetItems(oQuery);

if (results.Count == 0)
    return "";

foreach (SPListItem oListItem in results)
{
    return cleanValue(oListItem[returnColumnName].ToString());
}
return "";


will now look like this:

var results = list.GetItems(spQuery);
if (results.Count == 0)
    return "";

var item = results[0];
return CleanValue(item[returnColumnName].ToString());


Or in one return statement:

return results.Count > 0 ? CleanValue(item[returnColumnName].ToString()) : String.Empty;


Nitpicking:

  • Variable names:



  • theList should be replaced by listName or listTitle.



  • Avoid adding the o before the names, use spList and spQuery instead.

Code Snippets

var spQuery = new SPQuery
{
    Query = String.Format("<Where><Eq><FieldRef Name='{0}' /><Value Type='Text'>{1}</Value></Eq></Where>", matchColumnName , valueToMatch)
};
foreach (SPListItem oListItem in results)
{
    return cleanValue(oListItem[returnColumnName].ToString());
}
var spQuery = new SPQuery
{
    Query = String.Format("<Where><Eq><FieldRef Name='{0}' /><Value Type='Text'>{1}</Value></Eq></Where>", matchColumnName , valueToMatch),
    RowLimit = 1
};
SPListItemCollection results = oList.GetItems(oQuery);

if (results.Count == 0)
    return "";

foreach (SPListItem oListItem in results)
{
    return cleanValue(oListItem[returnColumnName].ToString());
}
return "";
var results = list.GetItems(spQuery);
if (results.Count == 0)
    return "";

var item = results[0];
return CleanValue(item[returnColumnName].ToString());

Context

StackExchange Code Review Q#140122, answer score: 4

Revisions (0)

No revisions yet.