c# - 检查以逗号分隔的字符串中的任何 id 是否与另一个字符串数组中的任何 id 匹配

标签 c# asp.net razor umbraco umbraco7

我正在使用 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/

相关文章:

c# - 抛出 HttpResponseException 未被 ExceptionFilterAttribute 捕获

c# - Paypal 沙箱与 asp.net c# 集成

c# - "BeginSession"方法未被调用或未成功 - QBFC SDK12 和 ASP.NET 网站

c# - 为什么我的 View 没有在 _Layout.cshtml 中呈现

asp.net-mvc-3 - 在所有 View 中共享布局内的下拉列表的方法是什么?

c# - 如何使用正则表达式更改字符串中的组

c# - 如何使用网络浏览器在链接列表中导航?

c# - 在同一个类中模拟一个方法

ASP.NET MVC5 以错误的格式存储日期

razor - 在Asp.net MVC4 Web应用程序中使用和创建帮助器