HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Customer search using LINQ followed by conditional filtering of results

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
linqsearchfollowedconditionalusingresultscustomerfiltering

Problem

I have a search function in my class which checks various class property values for null or certain values and queries the database based on those properties. This how my function looks like now:

```
public object searchCustomerList()
{
object partner = null;
try
{
using (var rep = new OrderEntities())
{
var results = (from par in rep.Partners
join term in rep.CustomerTerms on par.TERMID equals term.TERMID
select new
{
par.ID,
par.COMPANY,
par.CONTACT,
par.PRICECAT,
par.STATE,
par.TERMID,
par.PHONE,
term.TERMDESC
});
if (customerDetails.priceCategory != Prog.allObjectsIndex) {
results = results.Where(c => c.PRICECAT == customerDetails.priceCategory);
}
if (customerDetails.termID != Prog.allObjectsIndex) {
results = results.Where(c => c.TERMID == customerDetails.termID);
}
if (customerDetails.customerState != Prog.allObjectsIndex)
{
results = results.Where(p => p.STATE == customerDetails.customerState);
}
if (!string.IsNullOrWhiteSpace(customerDetails.companyName))
{
results = results.Where(p => p.COMPANY.Contains(customerDetails.companyName));
}
if (!string.IsNullOrWhiteSpace(customerDetails.contactPerson))
{
results = results.Where(p => p.CONTACT.Contains(customerDetails.contactPerson));
}

Solution

Filtering is actually done correctly, using the best and recommended approach. All LINQ queries are executed lazily, that is they are not executed until you start enumerating them. So all those .Where calls actually just register additional filtering of the records which would translate to entries in the where clause in SQL.

One thing to notice - the call to AsEnumerable() method before .OrderBy is potentially ineffective because it forces the ordering to be done on the client side instead of SQL. I would rewrite it as

results
        .OrderBy(x => x.COMPANY)
        .AsEnumerable()
        .Select(x => new
        {
            x.ID,
            x.COMPANY,
            x.CONTACT,
            PRICECAT=Prog.getPriceCategory()[(int) x.PRICECAT],
            STATE = Prog.getStatus()[(int)x.STATE],
            x.TERMDESC
        }).ToList();

Code Snippets

results
        .OrderBy(x => x.COMPANY)
        .AsEnumerable()
        .Select(x => new
        {
            x.ID,
            x.COMPANY,
            x.CONTACT,
            PRICECAT=Prog.getPriceCategory()[(int) x.PRICECAT],
            STATE = Prog.getStatus()[(int)x.STATE],
            x.TERMDESC
        }).ToList();

Context

StackExchange Code Review Q#125210, answer score: 3

Revisions (0)

No revisions yet.