Today we will discuss regarding Compare two objects in C# with example.
Let us take a example for Compare two objects in C# where we have a class called FileDesc which has property file name, we want to create a collection of FileDesc class which should contains only distinct file name.
To achieve this scenario we have to compare objects of class FileDesc.
Example:
public class CompareFileName : IEqualityComparer<FileDesc>
{
public bool Equals(FileDesc x, FileDesc y)
{
return (x.Fname == y.Fname) ? true : false;
}
public int GetHashCode(FileDesc obj)
{
// return 0;
if (Object.ReferenceEquals(obj, null)) return 0;
int hashFirst = obj.Fname == null ? 0 : obj.Fname.GetHashCode();
int hashLast = obj.Fname.GetHashCode();
return hashFirst ^ hashLast;
}
}
How to use it..
GridDetailed.ItemsSource = collection_files.Distinct(new CompareFileName());
Your feedback is always welcome.
Thanks, Happy coding 🙂