First of all, your SQL code is vulnerable to
SQL Injection[
^].
NEVER use string concatenation to build a SQL query.
ALWAYS use a parameterized query.
Secondly, to apply filters to a LINQ query, you just chain calls to the
Where
method:
var query = GetItems();
if (!string.IsNullOrEmpty(item))
{
query = query.Where(d => d.ItemName == item);
}
if (!string.IsNullOrEmpty(description))
{
query = query.Where(d => d.Description == description);
}
if (!string.IsNullOrEmpty(price))
{
query = query.Where(d => d.Price == price);
}
var inventoryData = query.ToList();
NB: Your
GetItems
method should return an
IQueryable<T>
instance, so that the filters are passed to the SQL query. Don't call
ToList
until you have built the entire query; otherwise, all of the data will be loaded into memory before the filtering takes place.
Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]
SQL injection attack mechanics | Pluralsight [^]