0

I have 3 search textbox values. i need to check string.isnullorEmpty for each variable and have to compare with the linq query.

My Text Values:

  1. Manufacturer

  2. Project Code

  3. PartNo

Conditions:

  1. if i search any one of the above i should get the result

  2. If i enter 3 box values i should get the result

  3. If i enter any 2 then i should get result.

My code as follows

if (!string.IsNullOrEmpty(manufacturer)) { var filteredResult = _entity.MaterialMasters.Where(x => x.Manufacturer == manufacturer); } if (!string.IsNullOrEmpty(projectcode)) { var filteredResult = _entity.MaterialMasters.Where(x => x.ProjectCode== projectcode); } if (!string.IsNullOrEmpty(part)) { var filteredResult = _entity.MaterialMasters.Where(x => x.Part== part); } 

To avoid multiple conditions how to make dynamic where clause for this? Please find out the solution for this..

1
  • you can create your own delegate extension method like public static IEnumerable<T> WhereTest<T>(this IEnumerable<T> , Func...) Commented Sep 27, 2016 at 17:21

3 Answers 3

3

He wants to get rid of the if statements and write this all as a linq query. I think you want something like this

.Where( s => (string.IsNullOrEmpty(manufacturer) | (s.Manufacturer == manufacturer)) && (string.IsNullOrEmpty(projectcode) | (s.ProjectCode == projectcode)) && (string.IsNullOrEmpty(part) | (s.Part== part)) ).ToList(); 
Sign up to request clarification or add additional context in comments.

Comments

1

You can just tag on multiple Where clauses

var filteredResult = _entity.MaterialMasters; if (!string.IsNullOrEmpty(manufacturer)) filteredResult = filteredResult.Where(x => x.Manufacturer == manufacturer); } if (!string.IsNullOrEmpty(projectcode)) filteredResult = filteredResult.Where(x => x.ProjectCode == projectcode); } if (!string.IsNullOrEmpty(part)) filteredResult = filteredResult.Where(x => x.Part == part); } 

They will work cumulatively, meaning that you can supply 1, 2 or 3 of the parameters and you'll get the appropriate results.

Comments

0
var filteredResult = _entity.Where( ent => (!string.IsNullOrEmpty(manufacturer) && ent.Manufacturer == manufacturer) || (!string.IsNullOrEmpty(projectcode) && ent.ProjectCode == projectcode) || (!string.IsNullOrEmpty(part) && ent.Part == part)); 

This will get you any result for manufacturer, projectCode and part in one place.

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.