我正在使用 Umbraco CMS (v7) 开发一个博客帖子系统,其中每个帖子都可以选择多个类别供用户在前端进行过滤;博客文章的类别存储为逗号分隔的字符串,使用类别 ID 作为值。
然后我计划使用查询字符串值过滤博客文章,并检查是否有任何博客文章类别与 ID 的任何查询字符串匹配。
这是一些示例数据:
Query String Categories = 1,5
Blog Post 1 Categories: 1,2,5,7
Blog Post 2 Categories: 6,7
Blog Post 3 Categories: 1,6
Blog Post 4 Categories: 3,4,5
我希望过滤返回博客文章 1、3 和 4,因为博客文章 2 的类别与查询字符串中的任何 ID 都不匹配。
这是我一直在处理的一些代码;它不起作用,但您可以看到我想要实现的目标:
var categories = !Request["c"].IsEmpty() ? Request["c"] : ""; // Query String Values
var categoryList = new List<int>(); // New integer list to add the split query string values to
IEnumerable<dynamic> Items = Umbraco.Content(1052).Descendants("BlogPost"); // Dynamic list of blog posts
if(!categories.IsEmpty()) // If the query string has some values
{
foreach(var cat in categories.Split(',')) // Split the query string…
{
categoryList.Add(Convert.ToInt32(cat)); … and convert and add these id's to my integer list
}
// The line that isn't really working, but the line i'm trying to add the filter to
Items = Items.Where(categoryList.Contains(x => x.searchCategories.Any())).ToList();
}
所以我的问题是:如何检查任何项目的类别是否与查询字符串值中的任何类别匹配以获得与我的示例数据相似的结果?
对于 Umbraco 开发人员:我正在使用多节点树选择器从博客文章中选择类别,内容仅限于我的“类别”节点列表。
最佳答案
如果 Items 填写正确,您应该使用以下代码获得您想要的结果:
var categoryList = categories.Split(',').Select(c=>int.Parse(c));
Items = Items.Where(x => categoryList.Contains(x.categoryId)).ToList();
关于c# - 检查以逗号分隔的字符串中的任何 id 是否与另一个字符串数组中的任何 id 匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29963963/