Querying list items
Sitefinity allows you to query for a specific list item by its ID. To search for specific list items based on any other property or criteria, see Finding list items.
NOTE: The code examples below work with the ID of the master version of the item and return the live version of the item. For more information about other scenarios, see Querying master and live versions.
Querying a single list item
When querying the live version of a specific list item by the ID of its master version, you must perform the following:
-
Get the list item.
First, get an instance of the master version of the list item that corresponds to the specified ID.
-
Get the live version.
The instance that corresponds to the ID argument is the master version of the list item. You can get the live version explicitly.
NOTE: The live version is used only when displaying the list item in a front-end scenario. To modify the list item, consider using the master version. To transfer the changes to the live version, publish the master version.
-
Return the list item.
Return the list item. If an item with the specified ID does not exist, or if it has no live version, you return null.
The following examples query the live version of a list item by the ID of its master version.
Native API
public ListItem GetListItemByIdNativeAPI(Guid masterListItemId)
{
ListsManager listsManager = ListsManager.GetManager();
ListItem listItem = listsManager.GetListItems().Where(i => i.Id == masterListItemId).FirstOrDefault();
if (listItem != null)
{
listItem = listsManager.Lifecycle.GetLive(listItem) as ListItem;
}
return listItem;
}
First, you get an instance of the ListsManager class. You get the specified list item by querying all items and filtering the collection by the IDof the list item. If the item exists, you get its live version. If no live version exists (i.e. the list item has not been published), null is returned. Finally, you return the list item.
To find the list item, you can also use the GetListItem method passing masterListItemId:
ListItem listItem = listsManager.GetListItem(masterListItemId);
Calling GetListItem(masterListItemId) throws an exception of type ItemNotFoundException, if there is no list item with the specified Id.
Fluent API
public ListItem GetListItemByIdFluentAPI(Guid masterListItemId)
{
int count = 0;
ListItem listItem = null;
App.WorkWith().ListItems().Where(i => i.Id == masterListItemId).Count(out count);
if (count > 0)
{
listItem = App.WorkWith().ListItem(masterListItemId).GetLive().Get();
}
return listItem;
}
First, you use the plural facade of the list item to assure that the item with the specified Id exists. Then, you use the GetLive method of the singular facade to get the instance of the live version. Finally, you return the list item.
See Also