2014-01-15 145 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