用于过滤的动态lambda表达式[英] Dynamic Lambda Expression For Filtering

本文是小编为大家收集整理的关于用于过滤的动态lambda表达式的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我在网页上有3个过滤条件

  1. 下拉源过滤
  2. 下拉类别的过滤
  3. 在StartDate Textbox和Enddate Textbox之间进行过滤

我目前正在将所有行从表中恢复,并将它们放入数据集中.我现在希望能够根据用户可能输入的上述过滤器的任何组合来过滤该数据集.也许用户选择不输入任何过滤器.

有人可以帮助我使用lambda表达式设置吗?

推荐答案

这是我在自己的代码中使用过滤器中使用的模式:

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();

本文地址:https://www.itbaoku.cn/post/1556900.html

问题描述

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?

推荐答案

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();