使用 LINQ to SQL 搜索字符串中的列表对象
本文关键字:列表 对象 字符串 搜索 LINQ to SQL 使用 | 更新日期: 2023-09-27 18:35:19
我有一个这样的字符串列表
List<string> list1 = new List<string>();
例如,我的列表是
{one , two , three , four , five}
在数据库中,我有这样的string
"five-six-seven-eight"
如何使用 Linq to SQL 在数据库中的字符串和列表之间进行搜索。例如,我的查询搜索应该是真的,因为"五"在两者上都很常见。我的查询是这样的:
var q = from p in m.ViewAbuseReports where
(list1.Contains(p.Abuse.ToString().Split('-')) || list1.Count == 0)
select new
{
Col2 = p.FirstName + " " + p.LastName,
Col3 = p.DateTakhalof,
Col4 = p.DateReturn
};
您可以考虑使用 LINQ Intersect
。
var q = from p in m.ViewAbuseReports
let ps = p.Abuse.ToString().Split('-')
let i = list1.Intersect(ps).ToList() //here you get if there is any intersect (common elements) between the two `IEnumerable`
where (i.Count > 0 || list1.Count == 0)
select new
{
Col2 = p.FirstName + " " + p.LastName,
Col3 = p.DateTakhalof,
Col4 = p.DateReturn
};
var q = from p in m.ViewAbuseReports where
(list1.Any(l => p.Abuse.ToString().Contains(l)) || list1.Count == 0)
select new
{
Col2 = p.FirstName + " " + p.LastName,
Col3 = p.DateTakhalof,
Col4 = p.DateReturn
};
如果 list1
中的任何字符串在 p.Abuse
中,则为真。这样你就不必照顾拆分字符串(这在数据库中很难做到)。