tags:

views:

541

answers:

1

I am trying to get this LINQ query to return exact matches if they exist or the "startswith" result if not. Right now it returns both.

example

SearchParam = "mundt" Results = Mundt, Mark | Mundt, Chris | Mundth, Lori

public static DataTable SearchPerson(string SearhParam)
    {
        var context = new ConnectDataContext(Properties.Settings.Default.ConnectConnectionString);
        var myQuery = (from person in context.tblPersons
                          where person.LastName.StartsWith(SearhParam) || person.LastName == SearhParam
                          orderby person.LastName
                          select new { person.PersonID, person.LastName, person.FirstName, person.SSN });

        var dataTable = myQuery.CopyLinqToDataTable();

        return dataTable;
    }
+2  A: 

Try:

        var persons = (from person in context.tblPersons
                          orderby person.LastName
                          select new { person.PersonID, person.LastName, person.FirstName, person.SSN });
        var filteredPersonsList = persons.Where(p=>p.LastName == SearhParam).ToList();
        if( filteredPersons.Count == 0 )
             filteredPersonList = persons.Where(p=>p.LastName.StartsWith(SearhParam))
                       .ToList();
        var dataTable = filteredPersonsList.CopyLinqToDataTable();

        return dataTable;

Note: it does 2 hits to the db, one to look for exact match, and one for the the startswith (if it didn't find the first).

Another option, is to grab them both, and then re-filter in memory.

eglasius
The 2 hits to the db is probably faster, because if the match exists you're done. If you filter in memory, you have to do O(n) search just to know if you still have work to do yet.
Joel Coehoorn
y, although that varies a lot per scenario. If the amount of people is considerably small, the round-trip delay will be longer. That said, I wouldn't sweat it, if [insert business] goes well there will be a lot of people in the system :)
eglasius
Since my scenario involves querying a local database I am fine with multiple calls.Thanks!
Refracted Paladin