LINQ query to return multiple results

I am trying to write a textbox that will search across 5 DB columns and return every result of a given search, eg. "Red" will return: red ball, red Williams, etc. Any examples or similar things that people have tried. My sample code for search.

Thank.

    ItemMasterDataContext db = new ItemMasterDataContext();

    string s = txtSearch.Text.Trim();
    var q = from p in db.ITMSTs
            where p.IMITD1.Contains(s) ||
             p.IMITD2.Contains(s) ||
             p.IMMFNO.Contains(s) ||
             p.IMITNO.Contains(s) ||
             p.IMVNNO.Contains(s)
            select p;

    lv.DataSource = q;
    lv.DataBind();

      

+1


source to share


3 answers


You can do something like this (syntax can be turned off)

using(var db = new ItemMasterDataContext())
{
    var s = txtSearch.Text.Trim();
    var result = from p in db.ITMSTs select p;

    if( result.Any(p=>p.IMITD1.Contains(s))
         lv.DataSource = result.Where(p=>p.IMITD1.Contains(s))
    else if ( result.Any(p=>p.IMITD2.Contains(s))
        lv.DataSource = result.Where(p=>p.IMITD1.Contains(s))

    lv.DataBind();
}

      



or you can use this Link or Link from MSDN.

Happy coding !!

0


source


The "q" in your example would be IQueryable<ITMST>

. I don't think the Datasource property of the WebControl knows what to do about it. try writing this line as:



 lv.DataSource = q.ToList();

      

+1


source


What you have is what people will do with linq. If you want more sophisticated and wild database maps, take a look at the SqlMethods class in System.Data.Linq.

@James Curran You can assign the DataSource property to q and it will work fine. The only difference is when the request is executed.

0


source







All Articles