Intersect list returning null

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

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

However, I am returning an empty list.

Both lists contain FileInfo found

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

And it is filtered by requests.

+6
source share
2 answers

I suspect that FileInfo does not override Equals / GetHashCode , so two different objects will be unequal, even if they refer to the same file. Three options:

  • Convert lists to paths if you don't need them, like FileInfo
  • Create an IEqualityComparer<FileInfo> and go to Intersect
  • Add IntersectBy in the same style as DistinctBy in MoreLINQ and offer it as a patch for the project :) (I thought we already had this, but apparently not ...)
+6
source

The links to FileInfo objects in your two lists will be different, so Intersect will create an empty list.

You will need to create a class that implements the IEqualityComparer<FileInfo> interface and passes an instance of this class to Intersect to get the expected result.

+3
source

Source: https://habr.com/ru/post/921942/


All Articles