为什么lambda表达式假设char而不是string

Dan*_*Dan 1 c# linq lambda

我使用lambda表达式有以下函数:

Func<string, DateTime> GetDateFromFileName
               = fileName => Path.GetFileNameWithoutExtension(fileName)
                                 .Select(s => DateTime.ParseExact(s.Substring(s.Length - 8, 8), "yyyyMMdd", null));
Run Code Online (Sandbox Code Playgroud)

但编译器抱怨a char没有.Length.Substring().为什么决定这s是一个char而不是一个string?有没有更优雅的方式来完成上述工作而不是投入几个.ToString()

Func<string, DateTime> GetDateFromFileName
               = fileName => Path.GetFileNameWithoutExtension(fileName)
                                 .Select(s => DateTime.ParseExact(s.ToString().Substring(s.ToString().Length - 8, 8), "yyyyMMdd", null));
Run Code Online (Sandbox Code Playgroud)

linq如何选择在lambda表达式中创建第一个变量的变量类型?

Dav*_*ton 5

GetFileNameWithoutExtension返回一个string你正在做的事情.Select.这意味着您将枚举字符串中的字符,因为字符串是char数组.

Linq将查看您正在使用的集合并使用内部对象的类型.

鉴于您的编辑,您可以将其更改为此

Func<string, DateTime> GetDatesFromFileNames
           = fileName =>
{
    String filenamenoext = Path.GetFileNameWithoutExtension(fileName); 
    return DateTime.ParseExact(filenamenoext.Substring(filenamenoext.Length - 8, 8), "yyyyMMdd", null));
}
Run Code Online (Sandbox Code Playgroud)