Ci Ty Chen
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
1
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
--- tags: LinQ, LinQ基礎 , C# --- # LINQ基礎 - IEquatable vs IEqualityComparer And IComparable vs IComparer 這四個介面通常是作用在參考型別. - 介面 IEquatable 和 IEqualityComparer 是用來檢查兩個參考型別是否**相等**. - 在取 Union , SequenceEqual , ToDictionary 等等的方法 , 我們可能會使用到它. 因為我們需要判兩個參考型別的物件是否相等. - 介面 IComparable 和 IComparer 是用來判斷兩個對象**誰大誰小**. - IComparable 和 IComparer 通常用於對一群參考型別的物件進行排序. - 在 Linq 方法中實際上會用到的是 **IEqualityComparer** 以及 **IComparer** - 另外兩個是順便 :crystal_ball: --- ### IEquatable IEquatable 是在 C# 2.0 加入的. 它的主要用途是**提供實作此介面的類別物件具有判斷自己與另一個與自己相同類別的物件是否相等的能力**. 所以實現 IEquatable 介面的類別都必須實作 Equals 方法. ``` bool Equals(T other); ``` ``` C# class Employee : IEquatable<Employee> { public int Id { get; set; } public string Name { get; set; } public bool Equals(Employee other) { return (Id == other.Id && Name == other.Name); } // 可以不 override public override bool Equals(object obj) { Employee employee = (Employee)obj; return (Id == employee.Id && Name == employee.Name); } // 可以不 override public override int GetHashCode() { return Id.GetHashCode() ^ Name.GetHashCode(); } } static void Main(string[] args) { Employee ob1 = new Employee(); Employee ob2 = new Employee(); Console.WriteLine(ob1.Equals(ob2)); // true // 如果沒 override bool Equals(object obj) , // 會使用Object.Equals - 依據記憶體位址是否相同(回傳 false) Employee a = new Employee(); object b = new Employee(); Console.WriteLine(a.Equals(b)); // true List<Employee> employees = new List<Employee> { new Employee { Id = 1, Name = "王" }}; List<Employee> employees2 = new List<Employee> { new Employee { Id = 3, Name = "綠" } , new Employee { Id = 1, Name = "王" } }; foreach (var emp in employees.Union(employees2)) { Console.Write(" " + emp.Name); // 輸出 : 王 綠 // 若是沒有實作 bool Equals(Employee other) 會因為記憶體位址不同 , // 被認為是不同實體 , 而輸出 : 王 綠 王 } } ``` 微軟的文件建議若是我們實作 IEquatable 介面 , 則順便 override Equals() & GetHashCode(). 以避免未預期的結果發生. --- ### IEqualityComparer IEqualityComparer是在 C# 2.0 加入的. 實作該介面的類別物件**具有判斷某相同類別的兩個物件是否相等的能力**. 實作IEquatable 的類別物件自身就能夠判斷自己是否與另外一個物件相等. 而實作 IEqualityComparer 的類別物件則是專門負責比較的比較器 , 通常是以不希望更改原類別為前提 , 但又希望可以比較該類別是否相等的狀況下使用. IEqualityComparer 必須實作下列兩個方法 1. bool Equals(T x, T y) : - 判斷兩物件相等的邏輯 3. int GetHashCode(T obj) : - 使用 hash 的方式加快比較相等的速度(在 key 相同的情況才會再進去 Equals去判斷兩物件是否相等) ```C# class Employee { public int Id { get; set; } public string Name { get; set; } } class EmployeeComparer : IEqualityComparer<Employee> { public bool Equals(Employee x, Employee y) { return x.Name.Equals(y.Name) && x.Id.Equals(y.Id); } public int GetHashCode(Employee obj) { return obj.Name.GetHashCode() ^ obj.Id.GetHashCode(); } } static void Main(string[] args) { List<Employee> employees = new List<Employee> { new Employee { Id = 1, Name = "王" } }; List<Employee> employees2 = new List<Employee> { new Employee { Id = 2, Name = "綠" }, new Employee { Id = 1, Name = "王" } }; foreach (var emp in employees.Union(employees2, new EmployeeComparer())) { Console.Write(" " + emp.Name); // 輸出 王 綠 // 若沒有使用 EmployeeComparer // 則輸出 王 綠 王 } Console.ReadKey(); } ``` --- ### IComparable IComparable 必須實現 CompareTo 方法 ```C# int CompareTo(Object obj) // 比較邏輯 ``` 1. 當呼叫物件 < 參數物件obj , 回傳負數 2. 當呼叫物件 > 參數物件obj , 回傳正數 3. 當呼叫物件 = 參數物件obj , 回傳零 ```C# class Employee : IComparable<Employee> { public int Id { get; set; } public string Name { get; set; } public int CompareTo(Employee other) { return Id.CompareTo(other.Id); } } static void Main(string[] args) { List<Employee> employees = new List<Employee> { new Employee { Id = 3, Name = "王" }, new Employee { Id = 1, Name = "綠" }, new Employee { Id = 2, Name = "王" }, }; employees.Sort(); // 沒實作 IComparable 會跳例外XD foreach (var employee in employees) { Console.WriteLine($"{employee.Id} {employee.Name}"); } Console.ReadKey(); } ``` ##### 輸出結果 Id = 1 Name = 綠 Id = 2 Name = 王 Id = 3 Name = 王 --- ### IComparer IComparer 使用在參考型態的自定義排序. (在 C# 3.5 前 , 可能在 Sort 方法的時候會使用) 但在 LinQ 的 ThenBy , OrderBy ...出來後 , 使用機率會少很多. LinQ 仍然有接受 IComparer 作為參數的方法. ```C# int Compare(T x, T y); ``` - 若 x < y 回傳 -1 - 若 x == y 回傳 0 - 若 x > y 回傳 1 ```C# class Employee { public int Id { get; set; } public string Name { get; set; } } class EmployeeCompare : IComparer<Employee> { public int Compare(Employee x, Employee y) { return x.Id.CompareTo(y.Id); } } static void Main(string[] args) { List<Employee> employees = new List<Employee> { new Employee { Id = 3, Name = "王" }, new Employee { Id = 1, Name = "綠" }, new Employee { Id = 2, Name = "王" } }; employees.Sort(new EmployeeCompare()); foreach (var employee in employees) { Console.WriteLine($"{employee.Id} {employee.Name}"); } Console.ReadKey(); } ``` ##### 輸出結果 1. 綠 2. 王 3. 王 --- ### 與 LinQ 的關聯 一些 LinQ 的方法可能會需要知道兩個項目是否相等或者需要比較兩個項目的大小. - 需要知道兩個項目是否相等 ToDictionary , ToHashSet , ToLookup , Contains , Distinct , SequenceEqual , Except , GroupBy , GroupJoin , Intersect , Join , Union - 需要比較兩個項目的大小 OrderBy , OrderByDescending , ThenBy , ThenByDescending , --- ### 參考 1. [Equals vs IEqualityComparer, IEquatable<T>, IComparable, IComparer](https://yetanotherchris.dev/csharp/equals-vs-iequatable-iequalitycomparer-icomparable-icomparer/) 1. [Comparing Complex Type With ==, Equals, IEquatable and IComparable in C#](https://www.c-sharpcorner.com/UploadFile/78607b/comparing-complex-type-with-equals-iequatable-and-icomp/) 1. [IComparable, IComparer And IEquatable Interfaces In C#](https://www.c-sharpcorner.com/UploadFile/80ae1e/icomparable-icomparer-and-iequatable-interfaces-in-C-Sharp/) 1. [使用原則(5) - IComparable<T>, IEquatable<T>](https://ithelp.ithome.com.tw/articles/10187848) 1. [What is the difference between IEqualityComparer<T> and IEquatable<T>?](https://stackoverflow.com/questions/9316918/what-is-the-difference-between-iequalitycomparert-and-iequatablet) 1. [What's the difference between IComparable & IEquatable interfaces?](https://stackoverflow.com/questions/2410101/whats-the-difference-between-icomparable-iequatable-interfaces) 1. [[C#] IComparable 和 IComparer](http://jengting.blogspot.com/2015/02/c-icomparable-icomparer.html) 1. [Implementing IComparable and IEquatable safely and fully](https://www.codeproject.com/Tips/408711/Implementing-IComparable-and-IEquatable-safely-and) 1. [談談C#的相等性(1)](https://blog.opasschang.com/2019/02/19/equality_in_csharp_1/) 1. [The Right Way to do Equality in C#](http://www.aaronstannard.com/overriding-equality-in-dotnet/) --- ### 補充 : 製造泛型的 IEqualityComparer ``` class EqualityComparer<TSource> : IEqualityComparer<TSource> where TSource : class { private PropertyInfo[] properties = null; public bool Equals(TSource x, TSource y) { if (properties == null) properties = x.GetType().GetProperties(); return properties.Aggregate(true, (result, item) => { return result && item.GetValue(x).Equals(item.GetValue(y)); }); } public int GetHashCode(TSource obj) { if (properties == null) properties = obj.GetType().GetProperties(); return properties.Aggregate(0, (result, item) => { return result ^ item.GetValue(obj).GetHashCode(); }); } } ``` ### 補充 : [EqualityComparer<T>.Default 屬性](https://docs.microsoft.com/zh-tw/dotnet/api/system.collections.generic.equalitycomparer-1.default?view=netframework-4.8) 依照泛型來決定回傳哪一個已被微軟定義好的比較器. - 大部分方法預設是使用此方法去製造比較器. - 未來我們自定義方法或是類別的時候 , 可使用此方法去幫我們產生比較器 ```C# public static Dictionary<TKey, TElement> MyToDictionary<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer) { if (source is null || keySelector is null || elementSelector is null) { throw new Exception("null exception"); } // 若 comparer 為 null 使用微軟定義的比較器. var d = new Dictionary<TKey, TElement>( comparer ?? EqualityComparer<TKey>.Default ); foreach (var element in source) { d.Add(keySelector(element), elementSelector(element)); } return d; } ``` --- ### Thank you! You can find me on - [GitHub](https://github.com/s0920832252) - [Facebook](https://www.facebook.com/fourtune.chen) 若有謬誤 , 煩請告知 , 新手發帖請多包涵 # :100: :muscle: :tada: :sheep:

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully