Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List Intersect returning null

I have two List<FileInfo> and I want to return the common FileItem between them.

List<FileInfo> outputList = new List<FileInfo>();
outputList = list1.Intersect(list2).ToList();

However, I'm getting back an empty List.

Both the lists contain FileInfo's found by

System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(startFolder);
IEnumerable<System.IO.FileInfo> fileList = 
dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);

And filtered by queries.

like image 978
Emlinie Avatar asked Aug 02 '12 12:08

Emlinie


1 Answers

I suspect that FileInfo doesn't override Equals/GetHashCode, so two distinct objects will be unequal even if they refer to the same file. Three options:

  • Convert the lists to paths if you don't need them as FileInfo
  • Create an IEqualityComparer<FileInfo> and pass that to Intersect
  • Implement IntersectBy in the same style as DistinctBy in MoreLINQ and propose it as a patch to the project :) (I thought we already had it, but apparently not...)
like image 132
Jon Skeet Avatar answered Sep 18 '22 12:09

Jon Skeet