Linq按日期时间字符串排序
Linq sort by string that is datetime
我有以下视图模型:
public class MvcFormsViewModel
{
public int RecCount { get; set; }
public List<Dictionary<string, string>> PageOfRecords { get; set; }
public MvcFormsViewModel()
{
PageOfRecords = new List<Dictionary<string, string>>();
}
}
我的控制器按以下方式对数据进行排序:
vm.PageOfRecords = vm.PageOfRecords.OrderBy(x => x.ContainsKey(sortValue) ? x[sortValue] :
string.Empty).Skip(startIndex).Take(endIndex - startIndex).ToList();
sortValue 从视图传递到控制器 - 它将是其中一个列的名称 - 也是字典中的一个键。
我的问题是,有时 "sortValue" 参数的值是时间戳,在这种情况下我希望 linq 排序为日期时间而不是字符串。我怎么能这样做?
类似于:
vm.PageOfRecords = vm.PageOfRecords
.Skip(startIndex)
.Take(endIndex - startIndex)
.OrderBy(x => x.ContainsKey(sortValue) ? DateTime.Parse(x[sortValue]) : DateTime.Min).ToList();
但如果数据集很大,这可能涉及大量转换。正如有人建议的那样,如果数据类型已经是 DateTime,这会使事情变得更容易
我有以下视图模型:
public class MvcFormsViewModel
{
public int RecCount { get; set; }
public List<Dictionary<string, string>> PageOfRecords { get; set; }
public MvcFormsViewModel()
{
PageOfRecords = new List<Dictionary<string, string>>();
}
}
我的控制器按以下方式对数据进行排序:
vm.PageOfRecords = vm.PageOfRecords.OrderBy(x => x.ContainsKey(sortValue) ? x[sortValue] :
string.Empty).Skip(startIndex).Take(endIndex - startIndex).ToList();
sortValue 从视图传递到控制器 - 它将是其中一个列的名称 - 也是字典中的一个键。
我的问题是,有时 "sortValue" 参数的值是时间戳,在这种情况下我希望 linq 排序为日期时间而不是字符串。我怎么能这样做?
类似于:
vm.PageOfRecords = vm.PageOfRecords
.Skip(startIndex)
.Take(endIndex - startIndex)
.OrderBy(x => x.ContainsKey(sortValue) ? DateTime.Parse(x[sortValue]) : DateTime.Min).ToList();
但如果数据集很大,这可能涉及大量转换。正如有人建议的那样,如果数据类型已经是 DateTime,这会使事情变得更容易