1

I'm new to ASP.Net and LINQ. I have a small project I'm working on. It basically consists of a screen with four text boxes, a listview control and a search button with one database table.

Each text box represents a certain field: Author, Title, Publisher, and Price. What I envision is that a user would input text in one, or more, of the fields and hit the search button. The program would then return whatever results could be found that match the user's criteria.

If I were using an SQL statement, I'd just select every record that matches any of the input fields (i.e. SELECT author, title, publisher, price FROM books WHERE...). However, I'm not quite sure how to do this with LINQ.

So, does anyone have a starting point for me? I've seen LINQ examples with one field as a limiter on the search:

public void SimpleSearch()
{
    DataClasses1DataContext dc = new DataClasses1DataContext();

    var q =
        from a in dc.GetTable<Books>()
        where a.Title == "1984"
        select a;

    dataGridView1.DataSource = q;
}

But I can't seem to find any other examples that use more than one limiter on the search. I'm beginning to think it isn't possible. If so, can someone recommend a different way for me to accomplish what I'm trying to do? Basically, I just want to search the table for fields that match the user's input and return the results in a listview. Any help would be greatly appreciate.

Kevin
  • 4,798
  • 19
  • 73
  • 120

2 Answers2

2

You should be able to use || as an OR delimiter:

public void SimpleSearch()
{
    DataClasses1DataContext dc = new DataClasses1DataContext();

    var q =
        from a in dc.GetTable<Books>()
        where a.Title == "1984" || a.Author == "Stephen King" || a.Price == 5.99m
        select a;

    dataGridView1.DataSource = q;
}

You can also use && to do an AND search instead of ||

Icemanind
  • 47,519
  • 50
  • 171
  • 296
1

I like to use contains to make the search a little more fuzzy and also I like to set everything to lowercase so there is no case sensitivity issues when performing the search.

public void SimpleSearch()
{
  DataClasses1DataContext dc = new DataClasses1DataContext();

  var search = txtSearch.Text.ToLower();

var q =
    from a in dc.GetTable<Books>()
    where a.Title.ToLower() == search ||
    a.Author.ToLower() == search ||
    a.Author.ToLower().Contains(search) ||
    a.Title.ToLower().Contains(search)
    select a;

dataGridView1.DataSource = q;
}
99823
  • 2,407
  • 7
  • 38
  • 60
  • Remember there are some languages/cultures where ToLower (and ToUpper) can be problematic. See f.ex. this SO post: http://stackoverflow.com/questions/234591/upper-vs-lower-case – larsts Sep 02 '15 at 10:41