代码之家  ›  专栏  ›  技术社区  ›  Ivan

将IEnumerable<Class>转换为List<string>

  •  0
  • Ivan  · 技术社区  · 7 年前

    我有一个 List<IOhlcv> 我需要拿到 string[] DateTime 来自 List :

    public interface ITick
    {
        DateTimeOffset DateTime { get; }
    }
    
    public interface IOhlcv : ITick
    {
            decimal Open { get; set; }
            decimal High { get; set; }
            decimal Low { get; set; }
            decimal Close { get; set; }
            decimal Volume { get; set; }
    }
    
    //candles is a List<IOhlcv>
    var candles = await importer.ImportAsync("FB");
    

    这里有什么

    string[] x = from p in candles
                 orderby p.DateTime ascending
                 select What goes here?
    

    列表 属于 Datetime

    var sd = candles.Select(i => i.DateTime).ToList();
    

    List<DateTime> to a List<String> 没有循环?

    我知道我可以这样做,但我正在努力避免循环:

    List<string> dateTimeStringList = new List<string>();
    
    foreach (var d in candles)
        dateTimeStringList.Add(d.DateTime.ToString());
    
     return dateTimeStringList ;
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Risto M    7 年前

    有没有办法把 List<DateTime> List<String> 循环?

    这就是你可以用它来做的 Linq Select :

    List<DateTime> list = new List<DateTime>();
    list.Add(DateTime.Now);
    var format = "yyyy MMMMM dd";
    var stringList = list.Select(r => r.ToString(format)).ToList();
    

    你可以替换 format 以上是你的最爱 DateTime format .

        2
  •  0
  •   KiraMiller    7 年前

    这个呢:

    string[] x = from p in candles
             orderby p.DateTime ascending
             select p.DateTime.ToString()
    

    你说得对,最后一个不会。我把它拿走了。