Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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?

share|improve this question

3 Answers 3

up vote 6 down vote accepted

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

So in your example:

logList = site.RootWeb.Lsits.TryGetList("Log Records");
share|improve this answer
1  
Thank for answer! I'm afraid some admin of site can change the title of list. –  IAfanasov Jan 20 '12 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 '12 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 '12 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 '12 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 '12 at 8:44

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) { .. }
share|improve this answer
logList = site.RootWeb.Lists.TryGetList("Log Records");
share|improve this answer
    
Please provide more details. –  Karthik Jaganathan May 8 at 9:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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