将一个集合转换为另一个集合(不是列表)

时间:2012-12-03 10:09:27

标签: c# linq

我有一个名为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。我们如何处理字符串集合?

参考

  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>

3 个答案:

答案 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());