gpt4 book ai didi

c# - 在运行时修改 linq 查询

转载 作者:行者123 更新时间:2023-11-30 13:38:39 25 4
gpt4 key购买 nike

问题陈述

假设我有一个搜索人名的查询:

var result = (from person in container.people select person)
.Where(p => p.Name.Contains(some_criterion)

这将被转换为包含以下 like 子句的 SQL 查询:

WHERE NAME LIKE '%some_criterion%'

这对性能有一些影响,因为数据库无法有效地使用名称列上的索引(如果我没记错的话,索引扫描与索引查找)。

为了解决这个问题,我可以决定只使用 StartsWith() 来代替,使用 like 子句生成查询,例如:

WHERE NAME LIKE 'some_criterion%'

这使 SQL Server 能够使用索引查找并以牺牲某些功能为代价提供性能。

我希望能够为用户提供一个选择:默认使用 StartsWith 的行为,但如果用户想要使用 Contains() 进行搜索“增加灵 active ”,则应该使用它。

我尝试了什么

我认为这是微不足道的,并继续在字符串上实现了一个扩展方法。但是当然,LINQ 不接受这个并抛出异常。

现在,我当然可以着手使用 if 或 switch 语句并为每种情况创建一个查询,但我更愿意“在更高层次上”或更一般地解决这个问题。简而言之:由于实际应用程序的复杂性,使用 if 语句来区分用例是不可行的。这会导致大量重复和困惑。我真的很想能够以某种方式封装不同的行为(Contains、StartsWith、EndsWith)。

问题

我应该去哪里寻找或寻找什么?这是 IQueryable 的可组合性案例吗?我很困惑!

最佳答案

与其让事情过于复杂,不如只使用 if 语句怎么样?

var query = from person in container.people 
select person;

if (userWantsStartsWith)
{
query = from p in query
where p.Name.Contains(some_criterion)
select p;
}
else
{
query = from p in query
where p.Name.StartsWith(some_criterion)
select p;
}

更新

如果您真的需要更复杂的东西,请尝试查看 LinqKit .它允许您执行以下操作。

var stringFunction = Lambda.Expression((string s1, string s2) => s1.Contains(s2));

if (userWantsStartsWith)
{
stringFunction = Lambda.Expression((string s1, string s2) => s1.StartsWith(s2));
}

var query = from p in container.people.AsExpandable()
where stringFunction.Invoke(p.Name, some_criterion)
select p;

我相信这可以满足您的要求

I'd really like to be able to encapsulate the varying behavior (Contains, StartsWith, EndsWith) somehow.

关于c# - 在运行时修改 linq 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15478769/

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