打扰一下,一个简单的问题:
我有一个字符串列表,字符串是一些文件的完整路径。我只想获取没有路径的文件名,既没有 each 字符串的扩展名(并更多地了解 lambda)
基于How to bind a List to a DataGridView control?中的lambda表达式我正在尝试以下内容:
FilesName = Directory.GetFiles(fbd.SelectedPath).ToList(); // full path
List<string> FilesNameWithoutPath = AllVideosFileNames.ForEach(x => Path.GetFileNameWithoutExtension(x)); // I want only the filename
AllVideosGrid.DataSource = FilesNameWithoutPath.ConvertAll(x => new { Value = x }); // to then bind it with the grid
错误是:
Can not convert void() to List of string
所以我想为 FilesName
中的每个字符串应用 Path.GetFileNameWithoutExtension()
。并感谢任何关于 Lamba 在这种情况下如何工作的额外描述。
最佳答案
ForEach
将对列表中的每个项目执行一些代码,但不会返回任何内容(参见: List<T>.ForEach Method
)。你要做的是Select
该方法的结果(参见: Enumerable.Select<TSource, TResult> Method
),看起来像:
List<string> FilesNameWithoutPath = AllVideosFileNames
.Select(x => Path.GetFileNameWithoutExtension(x))
.ToList();
关于c# - 使用 lambda,如何将现有函数应用于列表的所有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43288955/