我正在尝试编写一个 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/