[英]Custom string Comparison in C#
我想在C#中實現自定義字符串IComparer
並將其應用於ComboBox。
實際結果
如果我將ComboBox
的Sorted
屬性設置為true
,則輸出為:
A
AA
AAA
B
BB
BBB
通緝結果
排序算法的通緝行為如下(金融開發人員將理解為什么:)):
AAA
AA
A
BBB
BB
B
題
有可能嗎? 這里需要排序算法嗎?
PS:我不需要完整的代碼答案,我只需要了解它是如何完成的。
編輯
這是關於信用評級。 我在我的問題中省略了一些內容。 評級必須按以下順序排序:
XXX
XX+
XX
XX-
X+
X
X-
X in ('A','B','C')
和'A' > 'B' > 'C'
這是一個主要實現的版本:
public class MyComparer : IComparer<string>
{
public int Compare(string x, string y)
{
//todo null checks on input
var pairs = x.Zip(y, (a, b) => new { x = a, y = b });
foreach (var pair in pairs)
{
int value = pair.x.CompareTo(pair.y);
if (value != 0)
return value;
}
//if we got here then either they are the same,
//or one starts with the other
return y.Length.CompareTo(x.Length); //note x and y are reversed here
}
}
因此,這使用Zip
從每個對應的字符串中獲取字符對,直到結束,如果它們不相等則返回適當的值。 如果它超過了那個,那么一個字符串從另一個字符串開始。 對於傳統的字符串比較,我們只是按照與輸入參數相同的順序比較長度。 由於我們基本上是根據長度反轉順序,請注意x
和y
在最后一行交換。 這顛倒了比較邏輯。
假設這是用於信用評級,通常通過在CreditRating
類上設置“排序順序”列來完成,您可以使用該列對列表進行排序,然后將其指定為下拉列表的數據源。
但是,快速解決方法(基於有限的可能值)將按升序的第一個字母排序,然后按字符串降序的長度排序:
if(left[0] != right[0])
return left[0].CompareTo(right[0]);
else
return right.Length - left.Length;
如果您想要更多地控制訂單,另一種解決方法是以“正確”順序創建可能值的列表,然后使用它來對列表進行排序:
public class MyComparer : IComparer<string>
{
private static readonly string[] Ratings = new [] {
"CC","C","CCC-","CCC","CCC+",
"B-","B","B+","BB-","BB","BB+","BBB-","BBB","BBB+",
"A-","A","A+","AA-","AA","AA+","AAA"};
// reverse the order so that any strings not found will be put at the end.
public int Compare(string left, string right)
{
return Array.IndexOf(Ratings, right).CompareTo(Array.IndexOf(Ratings, left));
}
}
編寫IComparer,使其占用字符串,但每個字符進行比較,
if A[0] == B[0] go to the next character.
if B[1] == null or A[1] < B[1], return A < B.
if A[1] == null or B[1] < A[1], return B < A.
if equal...continue as needed
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.