c# - 在 umbraco 中构建 Linq 查询

标签 c# linq umbraco

我正在使用 Umbraco 的 uQuery 在 C# 中构建一个 Web 服务,它接受 2 个参数并返回一个包含搜索结果列表的 JSON 序列化字符串。

我传入一个包含搜索标签的字符串数组,例如[“红”、“蓝”]

public string GetResultsHttp(string[] tags)
{
    IEnumerable<Node> nodes;

    // first get all nodes that are of the right content type
    nodes = uQuery.GetNodesByType("MyPage");

    // if tags are passed in then limit the results to those tags
    if (tags.Length > 0)
    {
        nodes = nodes.Where(n => tags.Contains(n.Parent.GetProperty("tags").Value));
    }

    // return the node list as a serialized string

}

到目前为止一切顺利,可以返回包含我的任何标签的结果。

现在我想按日期限制结果。日期数组看起来像这样 ["201410", "201411"] 所以它是年,然后是月。

我想进一步将我的结果集限制为那些具有 myDate 属性的结果,其中月份和年份与我的日期数组中的任何月份和年份相匹配。

所以我的代码变成了这样:

public string GetResultsHttp(string[] tags, string[] dates)
{
    IEnumerable<Node> nodes;

    // first get all nodes that are of the right content type
    nodes = uQuery.GetNodesByType("MyPage");

    // if tags are passed in then limit the results to those tags
    if (tags.Length > 0)
    {
        nodes = nodes.Where(n => tags.Contains(n.Parent.GetProperty("tags").Value));
    }

    if (dates.Length > 0)
    {
        // the format of the incoming date
        string formatString = "yyyyMM";

        foreach (string dateTag in dates)
        {
            DateTime dt = DateTime.ParseExact(dateTag, formatString, null);
            nodes = nodes.Where(n => (dt.Month.Equals(n.GetProperty<DateTime>("myDate").Month)) && (dt.Year.Equals(n.GetProperty<DateTime>("myDate").Year)));
        }
    }

    // return the node list as a serialized string

}

以上显然适用于 1 个日期,但如果我传入 2 个日期,则一页不能有 2 个日期是理所当然的。

此外,我确信有一种更简单的方法可以实现这一点:)

谢谢 特拉维斯

最佳答案

当前您的查询确保日期等于dates 中的所有 日期。您希望它过滤 Any 日期在 dates 中的位置。

var nodes= uQuery.GetNodesByType("MyPage")
    .Where(n => tags.Contains(n.Parent.GetProperty("tags").Value)
    .Where(n => dates.Any(dateString => 
        DatesAreEqual(dateString, n.GetProperty<DateTime>("myDate"));

(DatesAreEqual 可以包含比较日期的所有逻辑,而不是试图内联所有解析/比较。)

关于c# - 在 umbraco 中构建 Linq 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20667823/

相关文章:

c# - 在多个 ASP.NET 子项目之间使用 AntiForgeryToken

c# - 无法将对象...转换为类型

linq - 使用 Linq 从列表字典创建映射

asp.net-mvc-3 - 如何防止 MVC 4 子应用程序继承父应用程序 (Umbraco MVC3) web.config

c# - Umbraco:Node、DynamicNode、Content 之间的区别

templates - 如何在 Umbraco 的页面上显示母版页的属性

c# - Observable.Interval 选择有状态服务会导致奇怪的行为

c# - 在 ASP.NET 中渲染服务器控件哪个更有效

c# - 在 Linq 表达式中使用方法

c# - LINQ 按多个属性分组并创建字典