如何按日期时间在datatable中搜索 [英] How to search in datatable by datetime
本文介绍了如何按日期时间在datatable中搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Hello Everyone,
我有一个DataTable,包含三列ID,Shift Start和Shift End
ID | Shift开始| Shift End
1 | 4/12/2018 7:00:00 AM | 4/12/2018 11:00:00 PM
现在问题是我要选择此日期和时间内的所有记录。我尝试了以下代码,但没有工作。
请帮帮我。
提前致谢。
我的尝试:
//这是我要搜索的持续时间的关键时间/时间范围
Hello Everyone,
I have a DataTable that contains three columns ID, Shift Start and Shift End
ID | Shift Start | Shift End
1 | 4/12/2018 7:00:00 AM | 4/12/2018 11:00:00 PM
Now the problem is i want to select all the records within this date and time. I tried the following code but not working.
Please help me out.
Thanks in advance.
What I have tried:
// This is key time / time frame in which duration i want to search
DateTime d = Convert.ToDateTime("4/12/2018 22:53");
string strD = d.ToString("hh:mm:ss tt");
// Presuming the DataTable has a column named Date.
string expression;
expression = "[Shift Start] > #4/12/2018 " + strD + "# AND [Shift End] < #4/12/2018 " + strD + "#";
DataRow[] foundRows;
// Use the Select method to find all rows matching the filter.
foundRows = dt.Select(expression);
// Print column 0 of each returned row.
for (int i = 0; i < foundRows.Length; i++)
{
MessageBox.Show(foundRows[i][1].ToString());
}
推荐答案
您可以像这样使用 LINQ :
You can use LINQ like this:
IEnumerable<DataRow> selectedRows = dt1.AsEnumerable()
.Where(row => (row.Field<DateTime>("Shift Start") <= d) && (d <= row.Field<DateTime>("Shift End")));
foreach (DataRow row in selectedRows)
{
Console.WriteLine("{0}, {1}", row[0], row[1]);
}
这是我的完整示例,在VS2017中使用.NET 4.5.1进行了测试:
Here is my complete example, tested in VS2017 with .NET 4.5.1:
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
namespace TestForm1
{
/// <summary>
/// Codeproject DataTable
/// </summary>
public partial class Form1 : Form
{
DataTable dt1 = new DataTable();
public Form1()
{
InitializeComponent();
Test();
}
private void Test()
{
// Add columns
dt1.Columns.Add("Shift Start", typeof(DateTime));
dt1.Columns.Add("employee_id", typeof(string));
dt1.Columns.Add("employee_name", typeof(string));
dt1.Columns.Add("Shift End", typeof(DateTime));
DateTime d = DateTime.Now;
// Add test data
dt1.Rows.Add(d.AddMinutes(-10), "1", "PRINCE", d.AddMinutes(-1));
dt1.Rows.Add(d, "2", "KING", d.AddMinutes(2));
dt1.Rows.Add(d.AddMinutes(1), "3", "PAUPER", d.AddMinutes(2));
IEnumerable<DataRow> selectedRows = dt1.AsEnumerable()
.Where(row => (row.Field<DateTime>("Shift Start") <= d) && (d <= row.Field<DateTime>("Shift End")));
foreach (DataRow row in selectedRows)
{
Console.WriteLine("{0}, {1}", row[0], row[1]);
}
}
}
}
与您的问题无关,但列中没有空格或表名 - 文件和文件夹名称相同 - 只是说: - )
Nothing to do with your question but never have spaces in column or table names - same goes for file and folder names - just sayin :-)
这篇关于如何按日期时间在datatable中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文