Reputation: 847
Here I have a list of string in sites1. I need to check the common items between sites1 and items1 and select the matching items from items1. Here is my code
string query = "/sitecore/content/*";
List<string> sites1 = Sitecore.Configuration.Settings.Sites.Select(x => x.StartItem.TrimStart('/')).ToList();
List<Item> items1 = Sitecore.Context.Database.SelectItems(query).Where(x => x.DisplayName.Contains(sites1)).ToList();
Any suggestion?
Edit: Here i am getting the error while selecting two items
var sites = Sitecore.Configuration.Settings.Sites.Select(f => new List<string>() { f.StartItem.TrimStart('/'), f.Language }).ToList();
List<Item> items = Sitecore.Context.Database.SelectItems(query).Where(x => sites.Contains(x.DisplayName.ToLower())).ToList();
Upvotes: 1
Views: 4694
Reputation: 6882
It should be the other way around: site1.Contains(x.DisplayName)
.
Also, compared to a list HashSet<string>
is more efficient for multiple look-ups, which becomes noticable as the number of items increases.
var sites1 = new HashSet<string>(Sitecore.Configuration.Settings.Sites
.Select(x => x.StartItem.TrimStart('/')));
var items1 = Sitecore.Context.Database.SelectItems(query)
.Where(x => site1.Contains(x.DisplayName))
.ToList();
EDIT:
I did not notice that SelectItems() returns IQueriable
. In that case I would re-write the second statement using IEnamerable.Any<>
extention method, which can be projected into server SQL query.
var items1 = Sitecore.Context.Database.SelectItems(query)
.Where(x=>sites1.Any(it=>it == x.DisplayName))
.ToList();
EDIT 2: Correcting the query from the edited question:
var sites1 = Sitecore.Configuration.Settings.Sites
.Select(x => new {DisplayName = x.StartItem.TrimStart('/'), Language = x.Language});
var siteNames = new HashSet<string>(sites1.Select(x=> x.DisplayName.ToLower());
var items1 = Sitecore.Context.Database.SelectItems(query)
.Where(x=>siteNames.Any(it=>it == x.DisplayName.ToLower()))
.ToList();
Upvotes: 2
Reputation: 17680
List<Item> items1 = Sitecore.Context.Database.SelectItems(query).Where(x => sites1.Contains(x.DisplayName)).ToList();
Upvotes: 2