我试图让这个LINQ查询返回完全匹配(如果存在)或“startswith”结果(如果不存在)。现在它返回两者。
SearchParam =“mundt” 结果= Mundt,Mark | Mundt,Chris | Mundth,Lori
public static DataTable SearchPerson(string SearhParam)
{
var context = new ConnectDataContext(Properties.Settings.Default.ConnectConnectionString);
var myQuery = (from person in context.tblPersons
where person.LastName.StartsWith(SearhParam) || person.LastName == SearhParam
orderby person.LastName
select new { person.PersonID, person.LastName, person.FirstName, person.SSN });
var dataTable = myQuery.CopyLinqToDataTable();
return dataTable;
}
答案 0 :(得分:3)
尝试:
var persons = (from person in context.tblPersons
orderby person.LastName
select new { person.PersonID, person.LastName, person.FirstName, person.SSN });
var filteredPersonsList = persons.Where(p=>p.LastName == SearhParam).ToList();
if( filteredPersons.Count == 0 )
filteredPersonList = persons.Where(p=>p.LastName.StartsWith(SearhParam))
.ToList();
var dataTable = filteredPersonsList.CopyLinqToDataTable();
return dataTable;
注意:它对数据库进行2次点击,一次查找完全匹配,一次用于startswith(如果没有找到第一次)。
另一种选择是抓住它们,然后在内存中重新过滤。