使用VB.NET的ICOMPARER
我有一张(我的班级)名单 我想对类中的属性(p property作为字符串)进行排序,并根据顺序确定的值进行排序 Dim MyListValues()作为字符串={“ccc”、“yyy”、“aaa”} 我想将IComparer界面用作:使用VB.NET的ICOMPARER,.net,vb.net,icomparer,.net,Vb.net,Icomparer,我有一张(我的班级)名单 我想对类中的属性(p property作为字符串)进行排序,并根据顺序确定的值进行排序 Dim MyListValues()作为字符串={“ccc”、“yyy”、“aaa”} 我想将IComparer界面用作: Public Class MyClass Public Property p As String 我想做: Private Class MyComparer Implements Icomparer(of MyClass ) Public Func
Public Class MyClass
Public Property p As String
我想做:
Private Class MyComparer Implements Icomparer(of MyClass )
Public Function Compare(x AS MyClass ) AS Integer Implements IComparer (Of MyClass ).Compare
Return ????
i want this order : 1) x.p = "ccc"
2) x.p = "yyy"
3) x.p = "aaa"
End FunctionEnd Class
how can I do that?
您知道要比较的值的域吗?也就是说,您是否知道它们将是“ccc”、“yyy”和“aaa”(或者其他值,但所有可能的值都提前知道) 如果答案是肯定的,那么我会考虑使用字典,其中键是已知值,值表示顺序。然后,在比较实现中,检索每个输入字符串的值并返回比较结果 请原谅我可怜的VB,因为我不使用VB.Net,我也不想发布一个C版本。我想你会明白的。实际上,您正在创建一个查找表,将已知字符串映射到每个字符串的“序号”值(或其在所有已知字符串集中的位置)。在比较MyClass的过程中,从正在比较的两个MyClass实例中的每一个实例中获取Prop1的值(因为这看起来像是您要比较的)。通过在字典中查找字符串,将每个字符串值转换为整数。然后可以从另一个整数中减去一个整数以获得比较结果 需要考虑的一些事项:
Private Class MyComparer Implements IComparer(of MyClass )
Private Dictionary dict = new Dictionary of (String, Integer) (System.StringComparer.OrdinalIgnoreCase)
Private Sub New()
dict.Add("ccc", 0)
dict.Add("yyy", 1)
dict.Add("aaa", 2)
End Sub
Public Function Compare(x AS MyClass, y AS MyClass ) AS Integer Implements IComparer (Of MyClass ).Compare
Boolean xb = String.IsNullOrWhitespace(x.Prop1)
Boolean yb = String.IsNullOrWhitespace(y.Prop1)
If xb And !yb Then Return -1 'x.Prop1 null or empty, y.Prop1 has a value
If !xb And yb Then Return 1 'x.Prop1 has a value, y.Prop1 has a value
If String.Compare(x.Prop1, y.Prop1, StringComparison.OrdinalIgnoreCase) = 0 Then Return 0
Integer xi = dict[x.Prop1]
Integer yi = dict[y.Prop1]
Return xi - yi
End Function
End Class
是的,我知道Dim myList()的值域为String={“ccc”,“yyy”,“aaa”}