YHTAN
YHTAN

Reputation: 686

LINQ search by text

I would like to do a linq, "When the txtKeyword.Text is empty, the query will return all data, or else it will return the data that contains the txtKeyword.Text."

        var search = from a in Context.data
                     where txtKeyword.Text.Trim().Count() > 0 ? a.Name.Contains(txtKeyword.Text.Trim()) : true
                     select a;

Error:
DbExpressionBinding requires an input expression with a collection ResultType.
Parameter name: input

How can I achieve it?

Upvotes: 2

Views: 5698

Answers (5)

Fede
Fede

Reputation: 4016

It seems the query expression is too complex for the query builder.

I would separate that code like this:

var search = Context.data;
string filter = txtKeyword.Text.Trim();
if (!string.IsNullOrEmpty(filter))
    search = search.Where(a => a.Name.Contains(filter));

Upvotes: 5

hawkstrider
hawkstrider

Reputation: 4341

You can just take the conditional check on txtKeyword out of the linq statement. Something like this

var search = string.IsNullOrEmpty(txtKeyword.Text)
            ? (from a in Context.data
                where a.Name.Contains(txtKeyword.Text.Trim())
                select a)
            : (from a in Context.data select a);

Upvotes: 0

Lukas Kabrt
Lukas Kabrt

Reputation: 5489

var searchText = txtKeyword.Text.Trim();
var returnAll = string.IsNullOrEmpty(searchText);

var search = from a in Context.data
                 where returnAll || a.Name.Contains(searchText)
                 select a;

Upvotes: 0

GendoIkari
GendoIkari

Reputation: 11914

var search =     from a in Context.data
                 where string.IsNullOrWhitespace(txtKeyword.Text) 
                 || a.Name.Contains(txtKeyword.Text.Trim())
                 select a;

Upvotes: 2

The Sharp Ninja
The Sharp Ninja

Reputation: 1041

var search = from a in Context.data
             where txtKeyword.Text.Trim().Any() 
                   || a.Name.Contains(txtKeyword.Text)
             select a;

Upvotes: 0

Related Questions