简体   繁体   中英

Search datatable using Linq to dataset

I have a datatable of user info. I am trying to perform a search that can be using last name, user's ID or user's role(s). I have a search textbox for name and ID and a search dropdown for user's role. Not all can be blank but any combincation can be used. I am using the following but don;t think it is right since it always returns the entire datatable:

dtUsers.CaseSensitive = false;
var results = dtUsers.AsEnumerable()
    .Where(r => r.Field<String>("LASTNAME").Contains(tbName.Text.Trim())
           ||   r.Field<String>("USERID").Contains(tbUserID.Text.Trim())
           ||   r.Field<String>("USERROLELIST").Contains(ddlRoles.SelectedItem.Text));            

dtUsers = results.CopyToDataTable();

What am I doing wrong? I also need to be able to do partial search on name and ID.

Modify your condition to check for empty string first (Use String.IsNullOrWhiteSpace ) and then apply your filter like:

var results = dtUsers.AsEnumerable()
    .Where(r =>(!String.IsNullOrWhiteSpace(tbName.Text) && r.Field<String>("LASTNAME").Contains(tbName.Text.Trim())
           || (!String.IsNullOrWhiteSpace(tbUserID.Text) &&r.Field<String>("USERID").Contains(tbUserID.Text.Trim())
           || r.Field<String>("USERROLELIST").Contains(ddlRoles.SelectedItem.Text));

Similarly you can do that with the last condition as well like:

(ddlRoles.SelectedItem != null && 
 !String.IsNullOrWhiteSpace(ddlRoles.SelectedItem.Text) && 
  r.Field<String>("USERROLELIST").Contains(ddlRoles.SelectedItem.Text)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM