我有一个名为DateTime
的{{1}}集合。我需要从reportLogs
创建一个Collection<T>
ShortDateString
。最有效的方法是什么?
Collection<DateTime>
修改:
问题是关于Collection<DateTime> reportLogs = reportBL.GetReportLogs(1, null, null);
Collection<string> logDates = new Collection<string>();
foreach (DateTime log in reportLogs)
{
string sentDate = log.ToShortDateString();
logDates.Add(sentDate);
}
;不是Collection of string
。我们如何处理字符串集合?
参考:
答案 0 :(得分:3)
如果您对IEnumerable<string>
感到满意:
IEnumerable<string> logDates = reportBL.GetReportLogs(1, null, null)
.Select(d => d.ToShortDateString());
您可以通过再拨打一次
轻松将其转为List<string>
List<string> logDates = reportBL.GetReportLogs(1, null, null)
.Select(d => d.ToShortDateString())
.ToList();
修改:如果确实需要您的对象为Collection<T>
,那么该类有a constructor which takes IList<T>
,那么以下内容将有效:
Collection<string> logDates = new Collection(reportBL.GetReportLogs(1, null, null)
.Select(d => d.ToShortDateString())
.ToList());
答案 1 :(得分:0)
var logDates= reportLogs.Select(d => d.ToShortDateString());
您可以选择添加.ToList()
答案 2 :(得分:0)
//Create a collection of DateTime
DateTime obj = new DateTime(2013,5,5);
List<DateTime>lstOfDateTime = new List<DateTime>()
{
obj,obj.AddDays(1),obj.AddDays(2)
};
使用List类 convertAll 方法转换为ShortDateString
//转换为ShortDateString
Lis<string> toShortDateString = lstOfDateTime.ConvertAll(p=>p.ToShortDateString());