我正在尝试在字符串中搜索特定值。
我想要做的是SPLIT字符串并查看每个值。 如果mySearch.EQUALS(split-string-value)然后返回ToList()中的记录。
这是我的代码..它返回ZERO RECORDS
// user search for sku = "2012"
// p.productMatch in DB = "2012,2012L,2012LR,2011"
var result = ctx.Products
.Where(p => p.clientID == Config.ClientID)
.Where(p => p.productMatch.Contains(sku))
.Select(v => new ProductView
{
productID = v.productID,
productMatch = v.productMatch,
productSKU = v.productSKU
}).ToList();
var results = from w in result
where w.productMatch.Split(',').Equals(sku)
select w;
return results.ToList();
答案 0 :(得分:4)
目前,在where w.productMatch.Split(',').Equals(sku)
行中,您将Split()
(字符串数组)的结果与单个字符串sku
进行比较。由于显而易见的原因,这失只需将其更改为:
where w.productMatch.Split(',').Contains(sku)
答案 1 :(得分:2)
在您的代码中,您正在对string[]
操作和Split
变量生成的sku
数组执行相等比较。由于两者的类型不同,因此相等比较永远不会成功。
您实际需要做的是将string[]
数组的每个元素与sku
进行比较:
var results =
from w in result
from part in w.productMatch.Split(',')
where part.Equals(sku)
select part;
如果要返回整个记录,请使用:
var results =
from w in result
where w.productMatch.Split(',').Any(part => part.Equals(sku))
select w;
或者,更好的是,使用@jimmy_keen建议的Contains
方法,以获得更简洁的代码。