PoliDev PoliDev - 2 months ago 17
C# Question

how to generate where condition without multiple if condition using linq query

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..

Answer

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