views:

49

answers:

1

I'm developing an application to perform searching on the basis of 4 search criteria:

  • Keyword (textbox)
  • Experience (dropdownlist)
  • Location (textbox)
  • Functional area (dropdownlist)

There is no mandatory field, so how to perform it?

+1  A: 

If I undertand the question... if you have access to LINQ, then it becomes simple:

(replace IQueryable<T> with IEnumerable<T> if you are using LINQ-to-Objects)

IQueryable<YourType> query = ctx.SomeObjects;

if(!string.IsNullOrEmpty(name)) {
    query = query.Where(x => x.Name == name);
}
if(activeOnly) {
    query = query.Where(x => x.IsActive);
}
if(minDate != DateTime.MinValue) {
    query = query.Where(x => x.Date >= minDate);
}
if(maxDate != DateTime.MinValue) {
    query = query.Where(x => x.Date <= maxDate);
}
var results = query.ToList();

If you are talking to a datawith with regular ADO.NET, you could either use dynamic query composition, or you could invoke an SP (or similar) that does the same internally - for example (of the first):

StringBuilder sql = new StringBuilder(
     "SELECT * FROM [SOME_TABLE] WHERE 1=1");
if(!string.IsNullOrEmpty(name)) {
    sql.Append(" AND [Name]=@name");
}
if(activeOnly) {
    sql.Append(" AND IsActive = 1");
}
if(minDate != DateTime.MinValue) {
    sql.Append(" AND [Date]>=@minDate");
}
if(maxDate != DateTime.MinValue) {
    sql.Append(" AND [Date]<=@maxDate");
}
// create connection, create command, add parameters, use ExecuteReader etc
Marc Gravell