9

Now i'm using same way to check does list exist by url

SPList logList  = null;
try
{
    logList     = site.RootWeb.GetListFromWebRelativeUrl("Lists/LogRecords");
}
catch { }
if (null != logList)
{DoSmt()}

This way isn't good at performance. Is where any safety way to check list existing?

3 Answers 3

11

SPWeb.Lists.TryGetList is probably what you're looking for.

So in your example:

logList = site.RootWeb.Lists.TryGetList("Log Records");
6
  • 1
    Thank for answer! I'm afraid some admin of site can change the title of list.
    – IAfanasov
    Jan 20, 2012 at 8:06
  • @JamesLove This method uses Title of a list. If the Title is changed through UI, will this code work?
    – Alexander
    Jan 20, 2012 at 8:26
  • 1
    Nope, in which case you would probably want to use the SPListCollection.GetList(Guid, Boolean) method to retrieve by List Guid - msdn.microsoft.com/en-us/library/ms470839.aspx
    – James Love
    Jan 20, 2012 at 8:29
  • 2
    @JamesLove as can I see the best approach is not to use this method :) As I understant the main part of try-catch execution time is an exception handling time. In this case you will have the perfomants problem only if the list does not exist. But this situation, as a rule, is a very rare. Am I right?
    – Alexander
    Jan 20, 2012 at 8:38
  • Well use. Remember the point of Exception handling as a whole is to deal with exceptions you expect to arise in the running of your code. So, I would use TryGetList first, then the method that triggers and exception, and deal with it appropriatly. Don't use magic strings in the TryGetList, see if you can make it configurable somehow.
    – James Love
    Jan 20, 2012 at 8:44
1

With a Guid of the list you should use

SPList list = sPwebObject.Lists.Cast<SPList>().FirstOrDefault(l => l.ID == yourGuidHere)
if (list != null) { .. }

or

if (sPwebObject.Lists.Cast<SPList>().Any(l => l.ID == yourGuidHere)) { .. }

With a Title of the list you should use

SPList list = sPwebObject.Lists.TryGetList(yourTitleHere);
if (list != null) { .. }
-2
logList = site.RootWeb.Lists.TryGetList("Log Records");
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.