2

I have a List<string> and a FileInfo[]. I need to know if the entire contents of the FileInfo[] are in the List<string>. What is the most LINQy and error-free way to do that?

I was doing this, based on responses here, it returns false however, I expected it to return true:

        // I want to know if all of these files are in the directory
        List<string> allFilesWanted = new List<string>();
        allFilesWanted.Add( "a1.txt" );
        allFilesWanted.Add( "a2.txt" );

        // Simulate a list of files obtained from the directory
        FileInfo[] someFiles = new FileInfo[3];
        someFiles[0] = new FileInfo("a1.txt");
        someFiles[1] = new FileInfo( "a2.txt" );
        someFiles[2] = new FileInfo( "notinlist.txt" );

        // This returns "false" when I would expect it to return "true"
        bool all = someFiles.All( fi => allFilesWanted.Contains<string>( fi.Name ) );

Thanks.

3 Answers 3

2

With your updated question:

var filenames=HashSet<string>(list);
fileInfoArray.All(fi=>filenames.Contains(fi.Name));

You might need to replace Name with FullName depending on what your HashSet contains.

And there is the issue of case sensitivity. You can supply a custom equality comparer when creating the hashset to achieve a case insensitive comparison(such as StringComparer.InvariantCultureIgnoreCase). The problem is that you can't know if a filename is case sensitive or not. That depends on the used file system. And even if you know it's case insensitive the locale used for case insensitive compares can vary.


Or just with Linq:

!fileInfoArray.Select(fi=>fi.Name).Except(list).Any();

Except uses a HashSet internally, so this is O(n)

Sign up to request clarification or add additional context in comments.

4 Comments

You don't have to lose the Except; you can do !fileInfoArray.Select(f => f.FullName).Except(list).Any()
@Ani Thanks for the hint. But there was no need to delete your answer, especially since mine was lacking a pure linq solution working with FileInfo and String
I also made a mistake (I reversed the query). You'd answered with Except before I could edit, so I decided to give it up :)
Note: You can use a StringComparer with Except as well (you mention it only with HashSet).
1
myFileInfoArray.All(fi => myList.Contains(fi));

Comments

1
List<string> fileNames = ... 
FileInfo[] fileInfos = ...  

var missing = fileInfos.Except(fileNames);
var anyMissing = fileInfos.Except(fileNames).Any()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.