user4881847
user4881847

Reputation:

Search keyword using linq in asp.net with c#back end

    List<search> alllist = wsWSemloyee.GetAllProject(); //where search is model class contains properties..
    string search_key = "%" + txtsearch.Text.Trim() + "%";


    List<search> result = new List<search>();
    foreach (search item in alllist)
    {
     var op = (
                     from a in alllist
                     where a.Sfirstname.Contains(search_key) || a.Slastname.Contains(search_key) || a.Smob.Contains(search_key) || a.Scity.Contains(search_key) || a.Sstate.Contains(search_key)
                     //where SqlMethods.Like(a.Sfirstname,search_key)||SqlMethods.Like(a.Slastname,search_key)||SqlMethods.Like(a.Scity,search_key)||SqlMethods.Like(a.Smob,search_key)||SqlMethods.Like(a.Sstate,search_key)
                     select a
                   );

   //  List<search> lst = op.ToList<search>();
        if (op != null)
        {
            result.Add(item);
        }
    }


    if (result.Count != 0)
    {
        dgv_searchreport.DataSource = result;
        dgv_searchreport.DataBind();// data grid view
    }

its not working... giving all result present in alllist.. //where search is model class contains properties..

Upvotes: 3

Views: 829

Answers (2)

iTechOwl
iTechOwl

Reputation: 150

May this helps you..

      string search_key = txtsearch.Text.Trim(); // instead "%" + txtsearch.Text.Trim() + "%";

        List<search> result = new List<search>();            
        var op = (from a in alllist
                     where a.Sfirstname.Contains(search_key) || a.Slastname.Contains(search_key) || ......
                     select a);

        if(op.Count() > 0)
        result = op.ToList();

Upvotes: 0

Jaroslav Kadlec
Jaroslav Kadlec

Reputation: 2543

I'ts because you are comparing if result of your linq query is not null and then adding variable from foreach clause. When any single item from allproducts will match condition then op will be never null and then whole collection will be contained in result. What you want is probably following:

var result = (from a in alllist
              where a.Sfirstname.Contains(search_key) 
                    || a.Slastname.Contains(search_key) 
                    || a.Smob.Contains(search_key) 
                    || a.Scity.Contains(search_key) 
                    || a.Sstate.Contains(search_key)
              select a).ToList();

That will pick all items which match condition and enumerate them to list.

Upvotes: 1

Related Questions