I perform the following code and the result is puzzling me
System.IO.DirectoryInfo rootDir =
new System.IO.DirectoryInfo(@"\\share\data");
// AllDir == 10 folders
System.IO.DirectoryInfo[] AllDir =
rootDir.GetDirectories("*.*", SearchOption.AllDirectories);
// JackDir == 2 folders
System.IO.DirectoryInfo[] JackDir =
rootDir.GetDirectories("Jack*.*", SearchOption.AllDirectories);
// MaryDir == 3 folders
System.IO.DirectoryInfo[] MaryDir =
rootDir.GetDirectories("Mary*.*", SearchOption.AllDirectories);
System.IO.DirectoryInfo[] otherDirectory =
AllDir.Except<DirectoryInfo>(MaryDir).Except(JackDir).ToArray();
And otherDirectory
in the end still has 10 folders...why not 5? How can I achieve this?
You are comparing DirectoryInfo
instances. They are not the same as they are returned by different calls to GetDirectories
.
You can define your own comparer for DirectoryInfo
comparing FullName
and use it in your calls to Except
.
public class DirectoryInfoComparer : IEqualityComparer<System.IO.DirectoryInfo>
{
public bool Equals(System.IO.DirectoryInfo x, System.IO.DirectoryInfo y)
{
if (object.ReferenceEquals(x, y))
return true;
if (x == null || y == null)
return false;
return x.FullName == y.FullName;
}
public int GetHashCode(System.IO.DirectoryInfo obj)
{
if (obj == null)
return 0;
return obj.FullName.GetHashCode();
}
}
System.IO.DirectoryInfo[] otherDirectory =
AllDir.Except<DirectoryInfo>(MaryDir, new DirectoryInfoComparer()).Except(JackDir, new DirectoryInfoComparer()).ToArray();
You need to provide a custom comparer, You see this behavior because it is tested equality against "Reference comparison" and of course they are different references.
Use Except method overload which takes IEqualityComparer
as parameter to achieve the desired output.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.