我的数据库中有一个名为Citites
的表。我想要检索名称中包含strings
列表中任何值的所有城市。
List<string> strings = new List<string>(new string[] {"burg", "wood", "town"} );
我试过了,但它只匹配字符串列表中的确切值。我需要找到包含例如town
的值,例如cape town
和townsend
List<City> cities = db.Cities.Where(c => strings.Contains(c.name));
修改
我正在使用LINQ to SQL
,Any()
似乎不支持此处:
本地序列不能用于查询的LINQ to SQL实现 除Contains运算符之外的运算符。
答案 0 :(得分:3)
假设您的LINQ提供程序支持它,这将满足您的需求 - 因为您没有提到您使用的是什么,我们无法对其进行测试。
List<City> cities = db.Cities.Where(c => strings.Any(s => c.name.Contains(s)));
详细说明:对于单个值(如Capetown
),您可以编写
strings.Any(s => "Capetown".Contains(s))
然后,您只需在当前Where
条件中应用此表达式,如初始代码示例所示。
答案 1 :(得分:1)
由于您提到您的LINQ提供程序在此上下文中不支持.Any(),因此这是一个更复杂的代码,可以动态构建查询表达式。
var strings = new [] { "burg", "wood", "town" };
// just some sample data
var cities = new[] { new City("Capetown"), new City("Hamburg"), new City("New York"), new City("Farwood") };
var param = Expression.Parameter(typeof(City));
var cityName = Expression.PropertyOrField(param, "Name"); // change the property name
Expression condition = Expression.Constant(false);
foreach (var s in strings)
{
var expr = Expression.Call(cityName, "Contains", Type.EmptyTypes, Expression.Constant(s));
condition = Expression.OrElse(condition, expr);
}
// you can apply the .Where call to any query. In the debugger view you can see that
// the actual expression applied is just a bunch of OR statements.
var query = cities.AsQueryable().Where(Expression.Lambda<Func<City, bool>>(condition, param));
var results = query.ToList();
// the class used in the test
private class City
{
public City(string name) { this.Name = name; }
public string Name;
}
但请注意,由于您在其他注释中提到strings
集合相当大,您应该考虑构建存储过程并将值作为XML参数传递给该过程(然后将XML作为表加载因为这种构建查询的方法可能很快会遇到某种类型的查询,并且操作数太多了,所以在查询中加入它。异常。
答案 2 :(得分:0)
我不确定你的LINQ提供程序是否支持它,但至少在LINQ-To-Objects中这是有效的:
List<City> cities = db.Cities.Where(c => strings.Any(s=> c.Name.Contains(s)));
答案 3 :(得分:0)
您需要检查城市名称是否包含列表中的任何字符串,而不是相反:
protected bool ContainsSubstring(string cityName, List<string> strings)
{
foreach(string subString in strings)
{
if (cityName.Contains(subString)) return true;
}
return false;
}
...
List<City> cities = db.Cities.Where(c => this.ContainsSubstring(c.name, strings));
答案 4 :(得分:0)
如果您发现它有很多循环,请尝试使用FUNC&lt;&gt;哪个会更好(性能)。我有一个样本:
List<string> _lookup = new List<string>() { "dE", "SE","yu" };
IEnumerable<string> _src = new List<string> { "DER","SER","YUR" };
Func<string, List<string>, bool> test = (i,lookup) =>
{
bool ispassed = false;
foreach (string lkstring in lookup)
{
ispassed = i.Contains(lkstring, StringComparison.OrdinalIgnoreCase);
if (ispassed) break;
}
return ispassed;
};
var passedCities = _src.Where(i => test(i, _lookup));
答案 5 :(得分:0)
var cities = from c in db.Cities.AsEnumerable()
from s in strings
where c.name.ToLower().Contains(s.ToLower())
select c.name;
答案 6 :(得分:0)
你有能力调用存储过程或sql吗? - 您可以使用SQL fulltextsearch,尤其是在您搜索多个术语时。它可能比在SQL中进行字符串比较要快得多。
http://technet.microsoft.com/en-us/library/ms142583.aspx
您可以通过string.Join(" ", strings)