2014-01-15 51 views
2

我有一個返回List<DateTime>但我的方法內運行的代碼讓我的方法的List<string>列表<string>列出<DateTime>

我怎麼能轉換List<string>List<DateTime>return線?

這基本上是一種方法,它會拍攝一張照片列表,並返回他們日期採取屬性的列表;

  //retrieves the datetime WITHOUT loading the whole image 
    public List<DateTime> GetDateTakenFromImage(List<string> path) 
    { 
     List<string> dateTaken = new List<string>(); 
     int cnt = 0; 
     while (cnt < path.Count()) 
     { 


      using (FileStream fs = new FileStream(path[cnt], FileMode.Open, FileAccess.Read)) 
      using (Image myImage = Image.FromStream(fs, false, false)) 
      { 

       PropertyItem propItem = myImage.GetPropertyItem(36867); 
       dateTaken[cnt] = r.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2); 
      } 
      cnt++; 
     } 

     return dateTaken; 

我從網站這個代碼,所以我不能完全肯定,如果我能做到他們返回到List<DateTime>

我認爲我可以提供答案,此代碼的工作,雖然。

謝謝!

+1

可能最好修改內部代碼以直接生成'DateTime'。向我們展示代碼。 –

+0

代碼將無法工作(對不起,它會編譯,但你會在運行時得到一個ArgumentOutOfRange異常),你試圖用索引器添加新項目到通用列表:'dateTaken [cnt] = ...'但你可以'噸,看到我的[問題](http://stackoverflow.com/questions/20840551/why-i-cant-add-items-to-the-generic-list-with-indexer) –

+0

@ Selman22謝謝!我原本在這個方法之外有一個循環,只是逐個提取每個日期所採用的prop。但是我在運行時遇到了ArgumentOutOfRange異常,不知道爲什麼!我想我可以解決這個問題,把方法放在方法 – teepee

回答

13

如果你知道所有的字符串的將正確地解析爲一個DateTime,你可以這樣做:

List<string> strings = new List<string>() { "2014-01-14" }; 

List<DateTime> dates = strings.Select(date => DateTime.Parse(date)).ToList(); 
+0

+1這是比我想到的更優雅的解決方案。 – pcnThird