LCJ
LCJ

Reputation: 22662

Convert one Collection to another Collection (not List)

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:

  1. Using LINQ to convert List<U> to List<T>
  2. LINQ convert DateTime to string
  3. Convert a datetime in a subcollection of collection and use it in LINQ to SQL
  4. convert Collection<MyType> to Collection<Object>

Upvotes: 0

Views: 1829

Answers (3)

sushil pandey
sushil pandey

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

Jamiec
Jamiec

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

Rik
Rik

Reputation: 29243

var logDates= reportLogs.Select(d => d.ToShortDateString());

Optionally you can add a .ToList()

Upvotes: 0

Related Questions