Reputation: 22662
I have a collection of DateTime
named reportLogs
. I need to create a Collection<T>
of ShortDateString
from this Collection<DateTime>
. What is the most efficient way to do it?
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);
}
EDIT:
The question is about Collection of string
; not about List of string
. How can we handle the Collection of string ?
REFERENCE:
Upvotes: 0
Views: 1829
Reputation: 762
//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)
};
use List class convertAll Method to convert to ShortDateString
//Convert to ShortDateString
Lis<string> toShortDateString = lstOfDateTime.ConvertAll(p=>p.ToShortDateString());
Upvotes: 0
Reputation: 136124
If you're happy with just IEnumerable<string>
:
IEnumerable<string> logDates = reportBL.GetReportLogs(1, null, null)
.Select(d => d.ToShortDateString());
You could turn this to List<string>
easily with 1 more call
List<string> logDates = reportBL.GetReportLogs(1, null, null)
.Select(d => d.ToShortDateString())
.ToList();
Edit: If you really need your object to be Collection<T>
then that class has a constructor which takes IList<T>
so the following will work:
Collection<string> logDates = new Collection(reportBL.GetReportLogs(1, null, null)
.Select(d => d.ToShortDateString())
.ToList());
Upvotes: 3
Reputation: 29243
var logDates= reportLogs.Select(d => d.ToShortDateString());
Optionally you can add a .ToList()
Upvotes: 0