gpt4 book ai didi

c# - 当两个值都添加了字符串时如何执行 Linq LIKE 或 Contains

转载 作者:太空宇宙 更新时间:2023-11-03 10:48:57 32 4
gpt4 key购买 nike

我正在尝试编写一个 Linq 查询以在数据库列中查找一个匹配值,该值是一个以逗号分隔的字符串值。为了确保我不匹配其中一个值的一部分,或者错过第一个或最后一个值,我通常在目标和源的开头和结尾添加一个逗号。不幸的是,这不适用于 Linq,而且我还没有弄清楚如何在这种情况下使用 SqlMethods.Like。我的代码:

int totalItems = 0;

var userList = from r in db.User
select r;

if (!string.IsNullOrEmpty(filter.department))
{
userList = userList.Where(s => s.department.Contains(filter.department));
}
if (!string.IsNullOrEmpty(filter.role))
{
// The following code that includes commas in the strings
// causes a runtime error regarding simple or enumerated objects:
userList = userList.Where(
r => (','+r.roles.Trim()+',').Contains(','+filter.role.Trim()+',')
);

// The following code works, but is not what I need to do the search properly:
//userList = userList.Where(s => s.roles.Contains(filter.role));
}

totalItems = userList.Count(); // here is where the error actually occurs

我不介意使用 SqlMethods.Like,但是在修改这样的查询时不知道如何使用它。

最佳答案

试试这个:

userList = userList.Where(
r => (r.roles.Split(',')).Any(o => o == filter.role)
);

关于c# - 当两个值都添加了字符串时如何执行 Linq LIKE 或 Contains,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22235615/

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