gpt4 book ai didi

c# - 在 umbraco 中构建 Linq 查询

转载 作者:太空宇宙 更新时间:2023-11-03 13:30:42 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com