How do I search for 4 main criteria?
1 answer
If I have a 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 data using regular ADO.NET, you can use dynamic query composition, or you can call SP (or similar) that does the same internally - for example (from 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
+1
a source to share