gpt4 book ai didi

c# - .Net Core C# - LINQ 查询运算符可以按逻辑分隔吗?

转载 作者:行者123 更新时间:2023-11-30 19:53:18 26 4
gpt4 key购买 nike

假设我有六个 LINQ 查询。每个查询都包含前一个查询使用的运算符,并向链中添加一个运算符:

Foo = await
(
_context.Foo
.Where(f => (Convert.ToDateTime(f.date1) - today).TotalDays < 31)
)
.ToListAsync();

Foo = await
(
_context.Foo
.Where(f => (Convert.ToDateTime(f.date1) - today).TotalDays < 31)
.Where(f => f.recordid == x)
)
.ToListAsync();

Foo = await
(
_context.Foo
.Where(f => (Convert.ToDateTime(f.date1) - today).TotalDays < 31)
.Where(f => f.recordid == x)
.Where(f => !StatusExceptionList.Contains(r.Status))
)
.ToListAsync();

Foo = await
(
_context.Foo
.Where(f => (Convert.ToDateTime(f.date1) - today).TotalDays < 31)
.Where(f => f.recordid == x)
.Where(f => !StatusExceptionList.Contains(r.Status))
.OrderBy(f => f.date1)
)
.ToListAsync();

Foo = await
(
_context.Foo
.Where(f => (Convert.ToDateTime(f.date1) - today).TotalDays < 31)
.Where(f => f.recordid == x)
.Where(f => !StatusExceptionList.Contains(r.Status))
.OrderBy(f => f.date1)
.ThenBy(f => f.date2)
)
.ToListAsync();

Foo = await
(
_context.Foo
.Where(f => (Convert.ToDateTime(f.date1) - today).TotalDays < 31)
.Where(f => f.recordid == x)
.Where(f => !StatusExceptionList.Contains(r.Status))
.OrderBy(f => f.date1)
.ThenBy(f => f.date2)
.ThenBy(f => f.recordid)
)
.ToListAsync();

我想将其压缩为一个查询,并在不同的 linq 运算符之间交织逻辑,如该伪代码所示,但这根本行不通。我四处搜索,不确定接下来要尝试什么:

Foo = await
(
_context.Foo
.Where(f => (Convert.ToDateTime(f.date1) - today).TotalDays < 31)
if (some logic)
{
.Where(f => f.recordid == x)
}
if (some different logic)
{
.Where(f => !StatusExceptionList.Contains(r.Status))
}
if (some different logic)
{
.OrderBy(f => f.date1)
}
if (some different logic)
{
.ThenBy(f => f.date2)
}
if (some different logic)
{
.ThenBy(f => f.recordid)
}
)
.ToListAsync();

谁能给我指出正确的方向,或者告诉我我是否试图以错误的方式解决这个问题?非常感谢!!!

最佳答案

只需将查询存储在单独的变量中:

IQueryable<Foo> query = _context.Foo
.Where(f => (Convert.ToDateTime(f.date1) - today).TotalDays < 31);

然后附加您的支票:

if (someCondition) {
query = query.Where(f.recordid == x);
}

等等。最后 - 运行查询:

Foo = await query.ToListAsync();

使用 OrderByThenBy - 检查查询是否已经是 IOrderedQueryable:

if (someCondition) {
var ordered = query as IOrderedQueryable<Foo>;
if (ordered != null)
query = ordered.ThenBy(x => x.field);
else
query = query.OrderBy(x => x.field);
}

关于c# - .Net Core C# - LINQ 查询运算符可以按逻辑分隔吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49582039/

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