Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# search query with linq

Tags:

c#

linq

I am trying to make a suitable linq query to accomodate my search functionality.

I have a table with the following columns: 'firstname' | 'lastname' | 'description'. with the following data: 'Peter' | 'Mulder' | 'This is a little description.'

My 'search' keyword could be something like: "peter" or "a little description".

Now if I use the following linq expression in lambda:

mycontext.persons
    .Where(t => 
        search.Contains(t.Firstname) || 
        search.Contains(t.Lastname) || 
        search.Contains(t.Description).Select(p => p)
    .ToList();

Now I get my result, when I use 'peter', but if I use 'pete' or 'a little description' I get no results. How can I make my linq expression, so it can search through the column data for matches?

like image 347
codingjoe Avatar asked Apr 26 '13 18:04

codingjoe


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C language basics?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


2 Answers

I think you just have it backwards:

mycontext.persons
    .Where(t => 
        t.Firstname.Contains(search) || 
        t.Lastname.Contains(search) || 
        t.Description.Contains(search))
    .ToList();
like image 77
Eren Ersönmez Avatar answered Sep 20 '22 20:09

Eren Ersönmez


One possible (but probably not the most optimized solution) would be to append all of your fields together and do a Contains on the search term., e.g.

var result = persons.Where(q => (q.Description + " " q.FirstName + " " q.LastName)
                    .ToLower()
                    .Contains(searchTerm.ToLower()))
                    .ToList();
like image 37
George Johnston Avatar answered Sep 17 '22 20:09

George Johnston