Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Equals and GetHashCode in C #

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how to use Equals and GetHashCode in C#. It is very detailed and has a certain reference value. Friends who are interested must finish it!

Equals and GetHashCode

Each implementation of Equals must follow the following conventions:

Reflexivity (Reflexive): x.equals (x) must return true. Symmetry (Symmetric): when x.equals (y) is true, y.equals (x) is also true. Transitivity (Transitive): if x.equals (y) returns true and y.equals (z) also returns true for any application values that are not null, then x.equals (z) must return true. Consistence: if you compare an object with another object multiple times, the result is always the same. As long as the x and y application objects are not modified, x.equals (y) continuously calls x.equals (y) to return the same value l. Non-null (Non-null): if x is not null,y and null, then x.equals (y) must be false

GetHashCode:

Two equal objects are equal when compared according to the equals method, so the hashcode method of either object must produce the same integer. When we do not modify the object, call hashcode multiple times to return the same integer. Execute multiple times in the same application, and the integers returned by each execution can be inconsistent. If two objects are not equal according to the equals method, the hashcode method of either object is called, an integer that is not the same. However, different objects produce different integers, which may improve the performance of the hash table.

IEqualityComparer implementation

Let's create a student class to further compare our object data.

Public class Student {public string Name {get; set;} public int Age {get; set;}}

We will implement our filtering through the distinct method through the following code.

Class Program {static void Main (string [] args) {List students = new List {new Student {Name = "MR.A", Age = 32}, new Student {Name = "MR.B", Age = 34}, new Student {Name = "MR.A", Age = 32}}; Console.WriteLine ("distinctStudents has Count = {0}", students.Distinct (). Count ()); / / distinctStudents has Count = 3 Console.ReadLine ();}}

What we need to achieve is to ignore the same data objects, but did not achieve our desired results. Because distinct compares references to objects by default. Therefore, this can not achieve our desired results. Then let's modify it to achieve our desired results.

By default, Equals has the following behavior:

If the instance is a reference type, Equals returns true only if the reference is the same. If the instance is a value type, Equals returns true only if the type and value are the same.

Distinct (IEnumerable, IEqualityComparer)

Returns non-repeating elements in the sequence by comparing values using the specified IEqualityComparer.

Type parameter

The element type of the TSource source.

Parameters.

The sequence from which source IEnumerable wants to remove repeating elements. The IEqualityComparer used by comparer IEqualityComparer to compare values.

Return

IEnumerable

An IEnumerable that contains non-repeating elements in the source sequence.

Let's look at the following code snippet

Public class StudentComparator: EqualityComparer {public override bool Equals (Student xForce Student y) {return x.Name = = y.Name & & x.Age = = y.Age;} public override int GetHashCode (Student obj) {return obj.Name.GetHashCode () * obj.Age;}}

In the above code snippet, if two Equals returns true and GetHashCode returns the same hash code, the two objects are considered equal.

Rewrite Equals and GetHashCode

Var stu1 = new Student {Name = "MR.A", Age = 32}; var stu2 = new Student {Name = "MR.A", Age = 32}; bool result = stu1.Equals (stu2); / / false because it's reference Equals

The result of the execution of the above code snippet is not the expected effect. We will further implement the code to achieve the desired results.

Public class Student {public string Name {get; set;} public int Age {get; set;} public override bool Equals (object obj) {var stu = obj as Student; if (stu = = null) return false; return Name = = stu.Name & & Age = = stu.Age;} public override int GetHashCode () {return Name.GetHashCode () * Age;}} var stu1 = new Student {Name = "MR.A", Age = 32}; var stu2 = new Student {Name = "MR.A", Age = 32} Bool result = stu1.Equals (stu2); / / result is true

We then use the LINQ Distinct method to filter and query, and we will check Equals and GetHashCode at the same time

List students = new List {new Student {Name = "MR.A", Age = 32}, new Student {Name = "MR.B", Age = 34}, new Student {Name = "MR.A", Age = 32}}; Console.WriteLine ("distinctStudents has Count = {0}", students.Distinct (). Count ()); / / distinctStudents has Count = 2

The above is all the contents of the article "how to use Equals and GetHashCode in C#". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report