【问题标题】:Check if any id's in a comma-separated string match any id's in another string array检查逗号分隔字符串中的任何 id 是否与另一个字符串数组中的任何 id 匹配
【发布时间】:2015-07-09 22:23:39
【问题描述】:

我正在使用 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 开发人员:我正在使用多节点树选择器从博客文章中选择类别,内容仅限于我的“类别”节点列表。

【问题讨论】:

  • 我假设如果你使用 categories = "1, 5" 那么 categories.Split 包含值 "1 ""5" (注意 1 后面的空格)。将foreach(var cat in categories.Split(',')) 替换为foreach(var cat in categories.Replace(" ","").Split(',')) 是否有效?编辑:代码运行正常还是出现异常?
  • 嗨 Nils,感谢您指出这一点 - 值之间实际上没有任何空格
  • 无法理解问题出在哪里。你能详细说明问题到底是什么“不起作用”吗?
  • 嗨 Reniuz,我已经编辑了我的问题。基本上我不知道如何使用我已经编写的代码来实现我的示例数据(它非常接近,但我无法让最后一行工作)

标签: c# asp.net razor umbraco umbraco7


【解决方案1】:

如果 Items 填写正确,您应该使用以下代码得到您想要的结果:

var categoryList = categories.Split(',').Select(c=>int.Parse(c));   
Items = Items.Where(x => categoryList.Contains(x.categoryId)).ToList();

【讨论】:

  • 这是否也会返回部分匹配项?
猜你喜欢
  • 2020-09-12
  • 1970-01-01
  • 1970-01-01
  • 2014-05-06
  • 1970-01-01
  • 1970-01-01
  • 2011-05-10
  • 1970-01-01
相关资源
最近更新 更多