尝试对这些日期进行排序
object[] Dates = pivotGridFieldDates.GetUniqueValues();
日期结果
9/10/2015
9/11/2015
9/2/2015
9/20/2015
9/25/2015
9/7/2015
9/8/2015
日期格式根据文化偏好进行更改,我想对这些对象数组日期进行排序....
where Datetype of "Dates" is {Name = "String" FullName = "System.String"}
我的代码
object[] Dates = pivotGridFieldDates.GetUniqueValues();
string result;
List<string> list=new List<string>();
var map = new List<String>();
foreach (var value in Dates)
{
string map1= Convert.ToString(value);
DateTime newdate = DateTime.ParseExact(map1, culture.ShortDatePattern,
CultureInfo.InvariantCulture);
result = newdate.ToString("yyyyMMdd");
map.Add(result);
}
map.Sort();
排序后,如何将此“地图”列表再次转换为对象[]周日期?并以与排序前相同的日期格式显示日期...
答案 0 :(得分:4)
您可以使用custom comparison delegate进行无需转换的排序,而不是转换,排序和转换,如下所示:
Dates.Sort((lhs, rhs) => {
var lhsDate = DateTime.ParseExact(Convert.ToString(lhs), culture.ShortDatePattern, CultureInfo.InvariantCulture);
var rhsDate = DateTime.ParseExact(Convert.ToString(rhs), culture.ShortDatePattern, CultureInfo.InvariantCulture);
return lhsDate.CompareTo(rhsDate);
});
答案 1 :(得分:2)
您只需使用OrderBy
(或者OrderByDescending
)对序列进行排序即可。也无需单独列表 - 仅Select
执行转换,如:
var listOfSortedStringDates = Dates.Select(v => DateTime.ParseExact( // parse
v.ToString(), // ToString as we have objects
culture.ShortDatePattern, CultureInfo.InvariantCulture))
.OrderBy(x=>x) // sort
.Select(newdate => newdate.ToString(culture.ShortDatePattern)) // back to string
.ToList();
Matt Johnson指出你真的需要解析OrderBy
- 不需要来回转换:
var listOfSortedStringDates = Dates
.OrderBy(v => DateTime.ParseExact(
v.ToString(), culture.ShortDatePattern, CultureInfo.InvariantCulture))
.ToList();