List Intersect returning null
Asked Answered
D

2

6

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.

Devoe answered 2/8, 2012 at 12:11 Comment(1)
FileInfo does not override Object.Equals so different instances will not be equal even if they refer to the same file. You will have to provide your own IEqualityComparer<FileInfo> to do the comparison.Suppository
F
6

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...)
Filet answered 2/8, 2012 at 12:16 Comment(3)
There is an example of exactly OP's situation and an example IEqualityComparer on this MSDN article.Unreel
@Bridge: Well, it's not a "good" example of IEqualityComparer IMO - that GetHashCode implementation is nasty :(Filet
I only meant the article was a good example, I didn't say the IEqualityComparer was a good example! :-)Unreel
F
3

The references to the FileInfo objects in your two lists will be different, and therefore Intersect will produce an empty list.

You would need to create a class that implements the IEqualityComparer<FileInfo> interface and pass an instance of this class to Intersect in order to get the result you expect.

Filiate answered 2/8, 2012 at 12:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.