【问题标题】:2sxc Linq query for Categories2sxc Linq 查询类别
【发布时间】:2017-04-17 09:19:44
【问题描述】:

我有实体:文档、类别、DocList

Documents 和 DocumentList 可以选择多个类别。

我想对属于一个或多个类别的文档进行过滤。

// all documents
var items = AsDynamic(App.Query["DocList"]["AllDocs"]);
// categories for filter
var fcat = Content.Category;

//linq query??
items = items.Where(d=>d.Category ....????....);

我可以以及如何制作这种过滤器?

Content.Category 是类别列表。

所以如果有任何类别,我想显示项目列表,而不仅仅是一个

类似这样的:linq where list contains any in list

【问题讨论】:

  • fcat的类型是什么?是合集吗?
  • 类别为 DynamicEntity

标签: c# linq 2sxc


【解决方案1】:

测试于:dnn 9.1.1 / 2sxc 9.14.0

我的最终代码:

@using System
@using ToSic.SexyContent
@using System.Collections.Generic
@using System.Linq
@{
    var items = AsDynamic(App.Data["Document"]);
    var tags = Content.Tags;
    items = items.Where(i => (i.Tags as List<DynamicEntity>).Any(c => ((List<DynamicEntity>)tags).Any(f => c.EntityId == f.EntityId)));
}
<div class="sc-element">
    <h1>@Content.Title</h1>
    @Edit.Toolbar(Content)
</div>
@foreach(var t in items)
{
    <div>@t.Title</div>
}

文档具有字段:标题(字符串)和标签(标签实体/多个)

内容是带有“标签”字段的“文档列表”(标签类型/多个)

这样我的代码就可以工作了。

【讨论】:

  • 完美。顺便说一句:您可能只需要第一个as List&lt;...&gt;,第二个c =&gt; ((List...) 可能不需要
【解决方案2】:

因此部分内容在 wiki https://github.com/2sic/2sxc/wiki/DotNet-Query-Linq

中进行了解释

但我必须承认,您的问题没有任何例子。我相信你想要这样的东西:

// filter - keep only those that have this Category
// note that the compare must run on the EntityId because of object wrapping/unwrapping
    items = items.Where(i => 
        (i.Category as List<dynamic>).Any(c => c.EntityId == fcat.EntityId))

所以这应该工作:)

如果 fcat 是一个列表,额外的解决方案应该是大约。像这样

// filter - keep only those that have this Category
// note that the compare must run on the EntityId because of object wrapping/unwrapping
    items = items.Where(i => 
        (i.Category as List<dynamic>).Any(c => fcat.Any(f => c.EntityId == f.EntityId)))

如果这导致错误,您可能需要将 fcat 转换为类似

((List<dynamic>)fcat).Any(...)

【讨论】:

  • 我之前犯了错误,这不起作用,因为 fcat = 动态实体列表。
  • 我需要类似的东西:stackoverflow.com/questions/10667675/…
  • 我做了一个更正,应该涵盖你的情况 - 有帮助吗?
  • 抱歉回复晚了。我尝试使用变体进行更新,但出现消息:错误:Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:无法将类型“System.Collections.Generic.List”转换为“System.Collections.Generic.List
  • 您使用的是 List 还是 List?你真的应该使用 List
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多