简体   繁体   English

在字符串列表中选择一个字符串

[英]Select a string in a list of strings linq

Here I have a list of string in sites1. 在这里,我有一个site1中的字符串列表。 I need to check the common items between sites1 and items1 and select the matching items from items1. 我需要检查site1和items1之间的公用项目,然后从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();

It should be the other way around: site1.Contains(x.DisplayName) . 应该是相反的方式: 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. 此外,与列表相比, HashSet<string>对于多次查找更有效,这随着项目数量的增加而变得明显。

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 . 我没有注意到SelectItems()返回IQueriable In that case I would re-write the second statement using IEnamerable.Any<> extention method, which can be projected into server SQL query. 在那种情况下,我将使用IEnamerable.Any<>扩展方法IEnamerable.Any<>第二条语句,该方法可以投影到服务器SQL查询中。

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: 编辑2:从已编辑的问题更正查询:

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();
List<Item> items1 = Sitecore.Context.Database.SelectItems(query).Where(x => sites1.Contains(x.DisplayName)).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM