【问题标题】:Convert one Collection to another Collection (not List)将一个集合转换为另一个集合(不是列表)
【发布时间】:2012-11-20 18:53:04
【问题描述】:

我有一个名为 reportLogsDateTime 集合。我需要从这个Collection<DateTime> 创建一个Collection<T>ShortDateString。最有效的方法是什么?

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;不是关于List 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>

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    如果您对 IEnumerable&lt;string&gt; 感到满意:

    IEnumerable<string> logDates = reportBL.GetReportLogs(1, null, null)
                                          .Select(d => d.ToShortDateString());
    

    您可以再拨打 1 次电话,轻松将其转为 List&lt;string&gt;

    List<string> logDates = reportBL.GetReportLogs(1, null, null)
                                          .Select(d => d.ToShortDateString())
                                          .ToList();
    

    编辑:如果您真的需要您的对象为Collection&lt;T&gt;,那么该类具有a constructor which takes IList&lt;T&gt;,因此以下将起作用:

    Collection<string> logDates = new Collection(reportBL.GetReportLogs(1, null, null)
                                          .Select(d => d.ToShortDateString())
                                          .ToList());
    

    【讨论】:

    • 问题是关于“字符串的收集”;不是关于“字符串列表”。我们如何处理“字符串集合”?
    • @Lijo - List&lt;T&gt; inherits ICollection&lt;T&gt; - 这意味着 List&lt;T&gt; 一个集合!
    • @Lijo - 另外Collection&lt;T&gt; 有一个构造函数,它采用IList&lt;T&gt; - 所以你总是可以将列表传递给上面的结果到一个新的集合。我会用这个更新答案。
    • @Lijo - 我很难想出更好的方法。无论你做什么,你都需要创建一个Collection&lt;T&gt; 的新实例并填充它。该解决方案只是通过扩充原始 Collection 来做到这一点
    • @Jamiec 您没有看到的点已包含在您编辑的答案中,希望现在清楚:) 当有人说 问题是关于“字符串集合”时;不是关于“字符串列表”,我希望像你这样有经验的人可以清楚地知道这个人在谈论Collection&lt;T&gt;,而不是关于通用术语collection,尤其是考虑到代码已经。
    【解决方案2】:
    var logDates= reportLogs.Select(d => d.ToShortDateString());
    

    您可以选择添加.ToList()

    【讨论】:

    • logDates 是目的地,而不是来源。
    【解决方案3】:
     //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

    //转换为短日期字符串

       Lis<string> toShortDateString =  lstOfDateTime.ConvertAll(p=>p.ToShortDateString());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-28
      • 2013-12-16
      • 2012-08-06
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多