Search code examples
c#stringlinqcontainsfileinfo

Returning a files name as string


I have a List< FileInfo > fileList and I am trying to make a variable containing the File name like the code below:

var newFileName = fileList.Select(x => x.Name).ToString();

Now I would expect the value of newFileName to be the files name but the value I get is this:

System.Linq.Enumerable+WhereSelectListIterator`2[System.IO.FileInfo,System.String]

I need to get the file name as a string becouse I want to check if another List< string > filesTemp already contains the newFileName.

if (!filesTemp.Contains(newFileName))

Why is the value as I mentioned and how can i get the actual Name of the file?

Thanks for any help


Solution

  • Select returns a lazily evaluated collection, you need to use FirstOrDefault to get the first value from the collection.

    var newFileName = fileList.Select( x => x.Name ).FirstOrDefault();
    

    But that only works for a single file name, you can use the Any method in the if statement instead to check whether or not any of the names from fileList are present in filesTemp.

    var isInTemp = fileList.Any( x => filesTemp.Contains( x.Name ) );