-1

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

Simon
  • 151
  • 2
  • 10

4 Answers4

1

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 ) );
1

We will get the name of the file from the property FileInfo.Name

As youhave not determined any files in select, You can get file name like following way.

fileList[0].Name

If you want to select file according to name,

fileList.Select(x => x.Name == name).ToList(); // Select file according to specific name.
Alfergon
  • 5,463
  • 6
  • 36
  • 56
AKHIL K A
  • 59
  • 6
0

Replace

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

by

IList<string> newFileName = fileList.Select(x => x.Name).ToList();

It will return a list of file names, then do your comparison

Aymeric
  • 1,089
  • 7
  • 10
-1

Seems like your problem is about aggregating.

I think the link below should be what you're looking for: Concat all strings inside a List<string> using LINQ

Community
  • 1
  • 1
Tjafaas
  • 129
  • 7