Finding two columns in LINQ to SQL?

I am trying to make a simple search method using LINQ to SQL in Visual Studio. In my database, I have the First Name and Last Name fields, and my search string is First Name. How can I make a simple LINQ query that searches for both fields?

In simple SQL, I would do something like this:

SELECT (Firstname + Lastname) as 'Fullname'
FROM   table
WHERE  Fullname LIKE '%searchstring%'
+5
source share
3 answers

The usual thing:

var users =
    from user in db.Users
    where user.FirstName.Contains(searchString) ||
        user.LastName.Contains(searchString)
    select user;

This, however, is not equivalent to your SQL query. The following is equivalent:

var users =
    from user in db.Users
    let fullName = user.FirstName + user.LastName
    where fullName.Contains(searchString)
    select user;
+18
source
var result = from p in db.Table
             let fullname = p.FirstName + " " + p.Lastname
             where fullname.Contains(searchString)
             select new { Fullname = fullname };
+4
source
// get all items from table where firstname like searchstring or lastname like searchstring
var result = from p in db.Table
             where (p.Firstname.Contains(searchString) || p.Lastname.Contains(searchString))
             select p;
+1
source

All Articles