我想使用Linq2Sql返回包含字符串列表中的值的所有行。 linq2sql类对象具有包含由空格分隔的单词的字符串属性。c#使用Linq2Sql查找表列中的匹配词
public class MyObject
{
public string MyProperty { get; set; }
}
例myProperty的值是:
MyObject1.MyProperty = "text1 text2 text3 text4"
MyObject2.MyProperty = "text2"
例如,使用一个字符串集合,我通过以下列表
var list = new List<>() { "text2", "text4" }
这将在我的例子返回上面两个项目,他们都包含“text2”值。
但是,我尝试了下面的代码,因为我的扩展方法无法评估Linq2Sql。
public static IQueryable<MyObject> WithProperty(this IQueryable<MyProperty> qry,
IList<string> p)
{
return from t in qry
where t.MyProperty.Contains(p, ' ')
select t;
}
我也写了一个扩展方法
public static bool Contains(this string str, IList<string> list, char seperator)
{
if (str == null) return false;
if (list == null) return true;
var splitStr = str.Split(new char[] { seperator },
StringSplitOptions.RemoveEmptyEntries);
bool retval = false;
int matches = 0;
foreach (string s in splitStr)
{
foreach (string l in list)
{
if (String.Compare(s, l, true) == 0)
{
retval = true;
matches++;
}
}
}
return retval && (splitStr.Length > 0) && (list.Count == matches);
}
我如何能做到这一点任何帮助或想法?
没有抱歉,这不起作用。我的自定义Contains方法无效(这只是解释我在做什么的一个例子),因为它不能被赋值,因为它不能被转换为SQL。 – David 2010-04-11 11:54:14
你说得对,我更新了答案。 – 2010-04-11 14:18:26
第二个被剪切的代码现在可以正常工作,只需使用示例数据库对其进行测试即可。 – 2010-04-11 14:20:34