大家好,
如果方法不好,谁能提出更好的解决方案, 我有一个 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 typeERROR2: 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 个小快捷方式:
Services字段值可以作为简单的竖线分隔的 GUID 字符串读取。- 使用
item["Services"]而不是item.Fields["Services"]将返回 如果没有值或字段不存在,则为空字符串,永远不会为 null。
如果你真的想使用更长的版本:
locations = locations.Where(x => ((MultilistField)x.Fields["Services"]).GetItems().Any(y => y.ID.Equals(serviceId)));
注意使用 Any 而不是第二个 Where。您没有选择 MultiList 项目。您正在检查任何匹配项。
