Snowy
Snowy

Reputation: 6122

Linq Match Array to List?

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.

Upvotes: 2

Views: 791

Answers (3)

CodesInChaos
CodesInChaos

Reputation: 108790

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)

Upvotes: 2

Mark Sowul
Mark Sowul

Reputation: 10600

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

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

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190915

myFileInfoArray.All(fi => myList.Contains(fi));

Upvotes: 1

Related Questions