0

I have a table called Items(Name,Description)

The user can search for items based on the name, the description or both. (The actual table has about 15 fields which can be searched on, but in this example, just keeping it to two).

This searches for both the name and description. But I need it to be one, the other or both.

var source = this.DbContext.Items; IQueryable<Item> items = source.Where(a => a.Name.Contains(item.Name)); items = items.Where(a => a.Description.Contains(item.Description)); return items.ToList(); 

This is the best I have come up with, but that second line seems kind of funky.

internal List<Item> Search(Item item) { var source = this.DbContext.Items; IQueryable<Item> items = source.Where(a=> a == a); if(!string.IsNullOrWhiteSpace(item.Name)) items = items.Where(a => a.Name.Contains(item.Name)); if(!string.IsNullOrWhiteSpace(item.Description)) items = items.Where(a => a.Description.Contains(item.Description)); return items.ToList(); } 
2
  • What are exactly looking for? Rid of this line IQueryable<Item> items = source.Where(a=> a == a); ? Commented Jul 1, 2018 at 17:48
  • Yes, I would like to eliminate that line. Commented Jul 1, 2018 at 18:06

1 Answer 1

1

If you want to rid of the second line in this snippet:

var source = this.DbContext.Items; IQueryable<Item> items = source.Where(a=> a == a); 

Just replace them with this:

// your Linq To Entities query is already an IQueryable<T> var items = from item in this.DbContext.Items select item; 

Or more simple remove the var keyword:

// There is an implicit conversion between DbSet<T> and IQueryable<T> // but you gain from it only if you remove the var keyword and not use the type inference IQueryable<Item> items = this.DbContext.Items; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.