I have a Droplist
field in an item that contains other items which are under the path /sitecore/content/Home
. I need to get the selected item from the Droplist
.
In this situation, I have to get the selected Item
by its name. Are there any other efficient ways of doing this, or is the way I am doing this okay?
public static Item GetItemByName(string itemName)
{
Database masterDb = Factory.GetDatabase("master");
Item homeItem = masterDb.GetItem("/sitecore/content/Home");
return homeItem.Axes.GetDescendants().FirstOrDefault(p => p.Name == itemName);
}
Droplist
is not the luckiest choice here. You should use Droplink
instead - it stores the item as ID, instead of storing item name only.
You should avoid using name as item identifier. There can be multiple items with the same name, even under same parent.
homeItem.Axes.GetDescendants()
is not really efficient method. It gets all the items which are under that node. You should avoid using it.
If you know that the item will be a child of the homeItem
, you can use:
homeItem.Children.FirstOrDefault(p => p.Name == itemName)
If that item can be at any level under the homeItem
, you can try to use index to get that item (checking item name equals to specified name and item full path starts with home page full path).