根据条件使用 Linq 在日期中搜索月份或年份
Search for month or year in a date using Linq based on condition
我想先说明一下我的情况:
我有一个 DataTable
,显示在 DataGridView
中。我还有一个 Textbox
来搜索特定列中的值。对于日期值,它看起来像这样(searchInDt 是我的数据表,getSelectedItem 是列名,searchBox 是文本框)
searchInDt.CaseSensitive = false;
var rowSources = (from myRow in searchInDt
.AsEnumerable()
.Where(myRow => myRow.Field<DateTime>(getSelectedItem)
.ToString()
.StartsWith(searchBox.Text))
select myRow);
if (rowSources.Any())
dataGridView1.DataSource = rowSources.CopyToDataTable();
所以这可行,但现在我有一个 CheckBox
,我可以在其中选择月份和年份。如果我想从 DateTime
值(月)的位置 3 或位置 6(年)开始搜索,它是如何工作的?
我试过跳过,但这不起作用。即使尝试 EndsWith
(这不完全是我正在寻找的)也不起作用。
无需检查 DateTime
的 string
值,您可以直接检查 DateTime
字段的 Month
/Year
属性。
根据CheckBoxselection设置isMonth
的值,然后
var isMonth = <true if Month is selected, false if Yaer is selected>;
var query = int.Parse(searchBox.Text);
var rowSources = searchInDt.AsEnumerable()
.Where(row => isMonth ? row.Field<DateTime>(getSelectedItem).Month == query
: row.Field<DateTime>(getSelectedItem).Year == query);
附带说明一下,您应该改用 RadioButton
,因为通常 CheckBox
用于 select 多个值,并且您不希望用户 select 月份和年份。
我想先说明一下我的情况:
我有一个 DataTable
,显示在 DataGridView
中。我还有一个 Textbox
来搜索特定列中的值。对于日期值,它看起来像这样(searchInDt 是我的数据表,getSelectedItem 是列名,searchBox 是文本框)
searchInDt.CaseSensitive = false;
var rowSources = (from myRow in searchInDt
.AsEnumerable()
.Where(myRow => myRow.Field<DateTime>(getSelectedItem)
.ToString()
.StartsWith(searchBox.Text))
select myRow);
if (rowSources.Any())
dataGridView1.DataSource = rowSources.CopyToDataTable();
所以这可行,但现在我有一个 CheckBox
,我可以在其中选择月份和年份。如果我想从 DateTime
值(月)的位置 3 或位置 6(年)开始搜索,它是如何工作的?
我试过跳过,但这不起作用。即使尝试 EndsWith
(这不完全是我正在寻找的)也不起作用。
无需检查 DateTime
的 string
值,您可以直接检查 DateTime
字段的 Month
/Year
属性。
根据CheckBoxselection设置isMonth
的值,然后
var isMonth = <true if Month is selected, false if Yaer is selected>;
var query = int.Parse(searchBox.Text);
var rowSources = searchInDt.AsEnumerable()
.Where(row => isMonth ? row.Field<DateTime>(getSelectedItem).Month == query
: row.Field<DateTime>(getSelectedItem).Year == query);
附带说明一下,您应该改用 RadioButton
,因为通常 CheckBox
用于 select 多个值,并且您不希望用户 select 月份和年份。