senzacionale
senzacionale

Reputation: 20936

linq to DB search with contains

C# linq to DB search

query = query.Where(x => x.Name.Contains(text));
query = query.Where(x => x.Lastname.Contains(text));
query = query.Where(x => x.Number.Contains(text));
query = query.Where(x => x.Address.Contains(text));
query = query.Where(x => x.Name.Contains(text));
query = query.Skip(page * limit).Take(limit);

how to write this in one line? I always get 0 rows event if in DB i have 5 of them.

Upvotes: 0

Views: 519

Answers (4)

NinjaNye
NinjaNye

Reputation: 7126

Take a look at a nuget package I have created

http://www.nuget.org/packages/NinjaNye.SearchExtensions

This will enable you to do the following (and much more)

Performing an OR search (text exists in any of the properties)

var query = query.Search(text, x => x.Name, 
                               x => x.LastName,
                               x => x.Address,
                               x => x.Number)
                 .Skip(page * limit)
                 .Take(limit);

Performing an AND search (text exists in all of the properties)

var query = query.Search(text, x => x.Name)
                 .Search(text, x => x.LastName)
                 .Search(text, x => x.Address)
                 .Search(text, x => x.Number)
                 .Skip(page * limit)
                 .Take(limit);

For more information take a look at the projects GitHub page or my blog posts

UPDATE: NinjaNye.SearchExtensions has now been updated to have a new fluent api meaning you can write the following:

var query = query.Search(x => x.Name, 
                         x => x.LastName,
                         x => x.Address,
                         x => x.Number)
                 .Containing(text)
                 .Skip(page * limit)
                 .Take(limit);

This will return records that have text contained in any of the defined properties

Upvotes: 0

Amir Sherafatian
Amir Sherafatian

Reputation: 2083

all constraints must be and together :

query = query
    .Where(x => x.Name.Contains(text) &&
        x.Lastname.Contains(text) &&
        x.Number.Contains(text) &&
        x.Address.Contains(text) &&
        x.Name.Contains(text))
    .Skip(page * limit)
    .Take(limit);

Upvotes: 0

Sergey Litvinov
Sergey Litvinov

Reputation: 7478

You can write:

query = query.Where(x => x.Lastname.Contains(text) || x.Number.Contains(text) || 
    x.Address.Contains(text) || x.Name.Contains(text))
    .Skip(page * limit).Take(limit);

Upvotes: 1

spajce
spajce

Reputation: 7092

You can use the Basic LINQ Query Operations in your task.

query.Where(x => x.Name.Contains(text) ||
    x.Lastname.Contains(text) ||
    x.Number.Contains(text) ||
    x.Number.Contains(text) ||
    x.Address.Contains(text)).Skip(page * limit).Take(limit).ToList();

Upvotes: 1

Related Questions