将List<string>转换为List<DateTime>

4
我有一个方法,它返回一个 List<DateTime>,但是我在方法内部运行的代码给了我一个 List<string>。 如何将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。请展示代码。 - p.s.w.g
那段代码不会起作用(很抱歉,它可以编译,但在运行时会出现ArgumentOutOfRange异常),您正在尝试使用索引器向通用列表添加新项:dateTaken[cnt] = ...,但您不能这样做,请参见我的问题 - Selman Genç
@Selman22谢谢!我最初在这个方法之外有一个循环,只是逐个提取每个日期拍摄属性。但是在运行时我遇到了ArgumentOutOfRange异常,而且完全不知道为什么!!!我认为把循环放在方法内部可以解决这个问题。 - teepee
请使用Add方法,而不是@teepee,即dateTaken.Add(...) - Selman Genç
@Selman22 终于!非常感谢,它起作用了,我一直无法弄清楚这个问题,让我疯狂。 - teepee
2个回答

21

如果您知道所有字符串都可以正确解析为DateTime,则可以这样做:

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

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

+1 这是一个比我想到的更优雅的解决方案。 - pcnThird

4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接