开发者

Can this implementation of an IEqualityComparer be improved? [closed]

Closed. This question is off-topic. It is not currently accepting answers.

Want to improve this question? Update the question so it's on-topic for Stack Overflow.

Closed 9 years ago.

Improve this question

I don't see any problems with this code, but it feels like I'm missing something. Maybe it is possible to reduce the number of lines. Or is there even a bug to be开发者_运维问答 fixed? I'm open to any suggestions.

public class NameComparer : IEqualityComparer<FileInfo>
{
    public bool Equals (FileInfo x, FileInfo y)
    {
        if (x == null) {
            return y == null;
        }

        if (y == null) {
            return false;   
        }

        return x.Name.Equals (y.Name);
    }

    public int GetHashCode (FileInfo obj)
    {
        return obj.Name.GetHashCode ();
    }
}


You should first return true if the FileInfo's equality operator returns true. Also, specify the type of string comparison you want to do. Presumably you'd want to ignore case, since these are filenames.

public class NameComparer : IEqualityComparer<FileInfo>
{
   public bool Equals(FileInfo x, FileInfo y)
   {
      if (x == y)
      {
         return true;
      }

      if (x == null || y == null)
      {
         return false;
      }

      return string.Equals(x.FullName, y.FullName, StringComparison.OrdinalIgnoreCase);
   }

   public int GetHashCode (FileInfo obj)
   {
      return StringComparer.OrdinalIgnoreCase.GetHashCode(obj.FullName);
   }
}


Comparing just the Name will only work if you're always comparing files of the same directory. I suggest comparing by FullName instead.

You can easily extend the scope of the equality comparer to directories by implementing it for FileSystemInfo, the base class of FileInfo and DirectoryInfo.

public sealed class FullNameComparer : IEqualityComparer<FileSystemInfo>
{
    public bool Equals(FileSystemInfo x, FileSystemInfo y)
    {
        if (x == y)
        {
            return true;
        }

        if (x == null || y == null)
        {
            return false;
        }

        return String.Equals(x.FullName.TrimEnd('\\'), y.FullName.TrimEnd('\\'), StringComparison.OrdinalIgnoreCase);
    }

    public int GetHashCode(FileSystemInfo obj)
    {
        return obj.FullName.GetHashCode();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜