c# - 如何转换项目并在 sitecore 中获取选定的项目?

标签 c# linq collections sitecore ienumerable

大家好,

如果方法不好,谁能提出更好的解决方案, 我有一个 IEnumerable<Item> locations其中包含多个位置。 IEnumerable 中的每一项包含 MultilistField . 我想通过他们的 IDs(GUID)选择项目, 我正在使用类似下面的内容,

locations = locations.Where(x => ((MultilistField)x.Fields["Services"]).GetItems().Where(y => y.ID.Equals(serviceId)));

但它给我错误:

ERROR1: Cannot convert lambda expression to delegate type 'System.Func<Sitecore.Data.Items.Item,bool>' because some of the return types in the block are not implicitly convertible to the delegate return type

ERROR2: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<Sitecore.Data.Items.Item>' to 'bool'

最佳答案

这是一种更简单的方法,可以绕过 MultiListField 对象的转换:

locations = locations.Where(item => item["Services"].Split('|').Contains(serviceId));

我在这里使用了 2 个小快捷方式:

  1. Services 字段值可以作为简单的竖线分隔的 GUID 字符串读取。
  2. 使用 item["Services"] 而不是 item.Fields["Services"] 将返回 如果没有值或字段不存在,则为空字符串,永远不会为 null。

如果你真的想使用更长的版本:

locations = locations.Where(x => ((MultilistField)x.Fields["Services"]).GetItems().Any(y => y.ID.Equals(serviceId)));

注意使用 Any 而不是第二个 Where。您没有选择 MultiList 项目。您正在检查任何匹配项。

关于c# - 如何转换项目并在 sitecore 中获取选定的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29714073/

相关文章:

Hibernate - 查询缓存/二级缓存不适用于包含子项的值对象

C#:将简单结构列表转换为 byte[]

c# - ServiceStack 使用对象序列化和反序列化字典

c# - 在 .net MVC 中渲染列表的子列表

c# - 将 linq 查询转换为 ObservableCollection

swift - 在 Swift 中使 CollectionViewCell 在突出显示时反弹

java - 从 SQL 查询检索时保留在列表中的顺序

c# - System.Web.HttpUtility.UrlEncode/UrlDecode ASP.NET 5 的替换

c# - 如何检查可变长度字符串以查看它们是否以数组中的任何内容开头

c# - 按可以为空的子记录值排序