1

I have 3 filter conditions on a web page

  1. Filter by dropdown Source
  2. Filter by dropdown Category
  3. Filter By Between StartDate textbox and EndDate textbox

I currently am getting all rows back from the table and putting them in dataset. I want to now be able to filter that dataset based on any combination of the above filters the user may input. Or maybe the user chooses to input no filters.

Can someone help me set this up using lambda expressions?

mellamokb
  • 56,094
  • 12
  • 110
  • 136
Nick LaMarca
  • 8,076
  • 31
  • 93
  • 152

1 Answers1

7

This is the pattern I use in my own code for applying filters:

var data = GetData();

var sourceFilter = SourceDropDown.Value;
if (!string.IsNullOrEmpty(sourceFilter))
    data = data.Where(d => d.Source == sourceFilter);

var categoryFilter = CategoryDropDown.Value;
if (!string.IsNullOrEmpty(categoryFilter))
    data = data.Where(d => d.Category == categoryFilter);

DateTime startDateFilter, endDateFilter;
if (DateTime.TryParse(TxtStartDate.Text, out startDateFilter) &&
    DateTime.TryParse(TxtEndDate.Text, out endDateFilter))
    data = data.Where(d => d.DT >= startDateFilter && d.DT <= endDateFilter);

return data.ToList();
mellamokb
  • 56,094
  • 12
  • 110
  • 136
  • @NickLaMarca I can't see any reason why it wouldn't. –  Mar 27 '12 at 15:36
  • This will apply all the filters simultaneously for any of the filters that have a valid value. Note that I'm assuming `GetData()` returns an object of type `IQueryable`, not `DataSet`, so you'll want to apply it on the data directly returned from your `DataContext`. – mellamokb Mar 27 '12 at 15:37
  • GetData returns a DataSet with one datatable – Nick LaMarca Mar 27 '12 at 15:39
  • Depending on the size of the data, if you're ok to filter the data just client-side, you can use something like `DataSet.Tables[0].Select().AsQueryable()` to get a collection of rows and apply the filters. However, if you want the filtering to be done server-side, you will need to apply the filters directly on an IQueryable, such as `MyContext.TableName.AsQueryable()`. – mellamokb Mar 27 '12 at 15:47
  • is this how you filter a datatable? – Nick LaMarca Mar 27 '12 at 15:50
  • var data = ds.Tables[0].AsEnumerable(); DateTime startDateFilter, endDateFilter; if (DateTime.TryParse(txtStartDate.Text, out startDateFilter) && DateTime.TryParse(txtEndDate.Text, out endDateFilter)) data = data.Where(d => d.Field("EventTimeStamp") >= startDateFilter && d.Field("EventTimeStamp") <= endDateFilter); – Nick LaMarca Mar 27 '12 at 15:50
  • This is overcomplicating things. Why do you need the DataSet in the first place? – mellamokb Mar 27 '12 at 17:10