使用linq或数据视图筛选器从c#中的DataTable中获取最高日期行



我可以获得最高的日期列值,但我想要整个单个数据行的日期最高。

DataTable dt = new DataTable();
dt.Columns.Add("City Name");
dt.Columns.Add("date");
dt.Rows.Add("Mumbai", "17/07/2018");
dt.Rows.Add("Surat", "17/02/2018");
dt.Rows.Add("Borivali", "17/10/2018");
dt.Rows.Add("Pune", "10/05/2018");
dt.Rows.Add("Valsad", "17/09/2018");
var query = dt.AsEnumerable().Max(x => x[1]);

首先,我建议更改格式:当使用DateTime时,为什么要使用String

DataTable dt = new DataTable();
dt.Columns.Add("City Name");
dt.Columns.Add("date");
dt.Rows.Add("Mumbai",   new DateTime(2018,  7, 17));
dt.Rows.Add("Surat",    new DateTime(2018,  2, 17));
dt.Rows.Add("Borivali", new DateTime(2018, 10, 17));
dt.Rows.Add("Pune",     new DateTime(2018,  5, 10));
dt.Rows.Add("Valsad",   new DateTime(2018,  9, 17));

您正在寻找不受标准Linq支持的ArgMax,但可以通过Aggregate:轻松地模拟

var row = dt
.AsEnumerable()
.Aggregate((s, a) => Convert.ToDateTime(s[1]) > Convert.ToDateTime(a[1]) ? s : a);
Console.Write($"{row[0]} {row[1]:dd/MM/yyyy}");

结果:

Borivali 17/10/2018

如果您坚持使用原始格式,则必须string解析为DateTime:

var row = dt
.AsEnumerable()
.Aggregate((s, a) => 
DateTime.ParseExact(s[1].ToString(), "d/M/yyyy", CultureInfo.InvariantCulture) >
DateTime.ParseExact(a[1].ToString(), "d/M/yyyy", CultureInfo.InvariantCulture) 
? s : a);

创建一个类PersonModel来携带DataTable中的属性。

您需要将"17/07/2018"字符串设置为DateTime,因此使用DateTime.ParseExact方法。

然后PersonModel类需要实现IComparable接口,告诉MAX函数如何比较。

public class PersonModel : IComparable
{
public string Name { get; set; }
public DateTime Dt { get; set; }
public int CompareTo(object obj)
{
var compareObj = obj as PersonModel;
return compareObj.Dt > this.Dt? 0:1;
}
}
var query = dt.AsEnumerable().Max(x => 
new PersonModel {
Name = x[0].ToString(),
Dt = DateTime.ParseExact(x[1].ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture)
}
);

最新更新