我在下面的代碼中使用了我的搜索邏輯,基本上,它在相應的文本框或下拉列表中存在輸入時評估字段,我的問題是代碼僅用於完全匹配,最好的實現方式是什麼a .Contains()搜索還是實現SQL LIKE搜索的搜索?如何在C#中的搜索表單中實現LIKE操作?
private void btnSearch_Click(object sender, EventArgs e)
{
bool ok_username = !txtUsername.IsBlank();
bool ok_firstname = !txtFirstname.IsBlank();
bool ok_lastname = !txtLastName.IsBlank();
bool ok_userlevels = cboUserLevels.IsItemInList();
_query = from _v
in Classes.Data.getdb().vUsers
where
_v.username ==(ok_username ? txtUsername.Text : _v.username) &&
_v.firstname == (ok_firstname ? txtFirstname.Text : _v.firstname) &&
_v.lastname == (ok_lastname ? txtLastName.Text : _v.lastname) &&
_v.userlevel == (ok_userlevels ? cboUserLevels.Text : _v.userlevel)
select _v;
gv.DataSource = _query ;
}
當我嘗試括在一。載()函數中的eval表達,它說,僅可以在客戶端上被求值的表達式可以被用作在功能。載的參數。謝謝!感謝任何建議!
好吧,
感謝Alex給我關於SQLMethods功能的想法。但是現在我會跟着桑德的鏈式表達樹的建議。如果任何人都可以縮短代碼,我會非常感激,因爲在這個解決方案中,我有兩組查詢,一組是針對靈活性的,另一組是針對精確搜索。再次感謝Alex和Sander!
private void btnSearch_Click(object sender, EventArgs e)
{
bool ok_username = !txtUsername.IsBlank();
bool ok_firstname = !txtFirstname.IsBlank();
bool ok_lastname = !txtLastName.IsBlank();
bool ok_userlevels = cboUserLevels.IsItemInList();
if (optMode.CheckedIndex == 0) //flexible search, the else part is the exact search
{
_query = (from _v
in Classes.Data.getdb().vUsers
where
_v.userlevel == (ok_userlevels ? cboUserLevels.Text : _v.userlevel)
select _v);
if (ok_username)
_query = _query.Where(x => x.username.Contains(txtUsername.Text));
if (ok_firstname)
_query = _query.Where(x => x.firstname.Contains(txtFirstname.Text));
if (ok_lastname)
_query = _query.Where(x => x.lastname.Contains(txtLastName.Text));
}
else
{
_query = (from _v
in Classes.Data.getdb().vUsers
where
_v.username == (ok_username ? txtUsername.Text : _v.username) &&
_v.firstname == (ok_firstname ? txtFirstname.Text : _v.firstname) &&
_v.lastname == (ok_lastname ? txtLastName.Text : _v.lastname) &&
_v.userlevel == (ok_userlevels ? cboUserLevels.Text : _v.userlevel)
select _v);
}
gv.DataSource = _query.ToList();
}
切換VB.NET並使用['Like'運算符](http://msdn.microsoft.com/en-us/library/swf8kaxw(v = vs.90).aspx);) –