IComparable क्या है
IComparable objects को compare होने देता है ताकि उन्हें sort किया जा सके, जैसे बच्चों को height के अनुसार लाइन में खड़े होना सिखाना। कोई object यह बताना सीखता है कि वह किसी दूसरे से पहले आता है या बाद में।
In this page:
Syntax
class ClassName : IComparable<ClassName>
{
public int CompareTo(ClassName other)
{
return this.Value.CompareTo(other.Value); // <0, 0, >0
}
}
IComparable
IComparable<T> एक single method, CompareTo, define करता है, जो objects को अपना natural ordering define करने देता है।
इसे implement करना किसी type को बिना किसी अतिरिक्त comparer के Array.Sort या List<T>.Sort से sort होने देता है। CompareTo less-than, equal, या greater-than बताने के लिए negative, zero, या positive return करता है।
Note:
IComparable<T> implement करें जब भी किसी type का एक स्पष्ट natural sort order हो, जैसे कोई numeric score।उदाहरण: IComparable
using System;
using System.Collections.Generic;
class Player : IComparable<Player>
{
public string Name;
public int Score;
public Player(string name, int score)
{
Name = name;
Score = score;
}
public int CompareTo(Player other)
{
return Score.CompareTo(other.Score);
}
}
class Program
{
static void Main(string[] args)
{
List<Player> players = new List<Player>
{
new Player("Ana", 50),
new Player("Ben", 90),
new Player("Cid", 20),
};
players.Sort();
foreach (Player p in players)
{
Console.WriteLine($"{p.Name}: {p.Score}");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- class पर
: IComparable<Player>declare करना भूल जाना, जिससेlist.Sort()एकInvalidOperationExceptionफेंकता है क्योंकि items compare नहीं हो सकते। CompareToसे गलत sign return करना, जिससे list विपरीत order में sort होती है; इसे negative number देना चाहिए अगर यह object पहले आता है, equal होने पर zero, और अन्यथा एक positive number।CompareToकोScore - other.Scoreके रूप में implement करना, जो बड़ी values के लिए overflow हो सकता है और गलत result दे सकता है; इसके बजायScore.CompareTo(other.Score)का उपयोग करें।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: