在数据集中查找最早的日期时间元素 [英] Find the earliest Date time Element in a Dataset

查看:383
本文介绍了在数据集中查找最早的日期时间元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较数据集行的日期时间元素和我的要求,如:

我想获取查询返回的所有i行数的所有日期,并将其存储在数组或列表之类的东西中(您提出了什么建议?).然后比较这些日期,找到所有元素中最早/最新的ItemArray.

例如,下面给出的数据集行数为5

I want to compare the date time elements of rows of a dataset and my requirement something like :

i want to fetch the all the dates for all i number of rows returned by the query and store in an array or list or something(what ever you suggest?). Then compare these dates and find the ItemArray which is the earliest/newest of all the elements.

For Instance , below gives me a Data Set row count of 5

ds.Tables[0].Rows[i]ItemArray["DateTime"].ToString()).ToString("dd/MM/yyyy");



我得到以下日期
2012年5月7日
23/06/2011
13/11/2013
2014年4月24日
2014年1月30日

从数据集中获取日期后,我想对它们进行比较并找出最早的日期.

在这里,我应该得到的结果是 24/04/2014 ,因为它是最新的.



and i get following dates
05/07/2012
23/06/2011
13/11/2013
24/04/2014
30/01/2014

Once I fetch the dates from the dataset , I want to compare these and find which is the earliest one.

Here I should get 24/04/2014 as my result as it is the newest.

推荐答案

var minDate =ds.Tables[0].AsEnumerable().Select(record => record.Field<datetime>("DateTime")).Max();


首先,这不是您的代码,因为(a)不会编译,(b)是即使您修复了编译错误,它也毫无意义-当给定要使用的字符串时,您希望ToString与日期相关的格式字符串做什么?因为将其格式化为DateTime不在其可以执行的操作的列表中...

DataRow值和DataRowCollections不能直接由C#中的排序工具使用-您确实需要将数据提取到可以轻松排序的类(以及该类的集合)中,并以原始格式保存数据那-在这种情况下,这意味着DateTime值,而不是字符串,因为它们更容易排序.

因此,请查看您的代码,计算出要输入到DataTable中的数据,并考虑创建一个包含该信息的类.然后从DataTable加载该集合,并对集合进行排序.
First things first: that isn''t your code, as that code (a) won''t compile and (b) is pretty pointless even if you fix the compilation errors - what do you expect ToString with a date related format string to do when given a string to play with? Because format it as a DateTime is not in the list of things it will do...

DataRow values and DataRowCollections are not directly usable by the sort facilities in C# - you really need to extract the data into a class (and a collection of that class) that can sort easily, and keep the data in it''s native format for that - in this case that means DateTime values, not strings as they are much much easier to sort.

So look at your code, work out what data you are feeding into the DataTable and consider creating a class that holds that information. Then load a collection of that from the DataTable, and sort the collection.


这篇关于在数据集中查找最早的日期时间元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆