How can i get file name list from
List<FileInfo> FileInfoList;
by using LINQ? I want all file names in
List<string> FileNames;
list. I don't want to construct a foreach loop and don't want to add file names iteratively.
You can use the Select extension method:
List<string> FileNames = FileInfoList.Select(x => x.Name).ToList();
However, if you don't really need it to be a List<T>
, you can probably take advantage of Linq's lazy-execution ability by simply omitting the ToList
method:
IEnumerable<string> FileNames = FileInfoList.Select(x => x.Name);
Or if you prefer query syntax:
IEnumerable<string> FileNames = from x in FileInfoList select x.Name;
If you only want the FileNames in FileNames list, try:
FileInfoList.ForEach(x =>
FileNames.Add(Path.GetFileName(x.FullName)));
If you want complete file paths in FileNames try
FileInfoList.ForEach(x =>
FileNames.Add(x.FullName));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.