我有一个(Myclass的)列表,我想根据我的类中的一个属性(p属性为字符串)进行排序,并根据顺序确定值Dim myListeValues() AS String = {"ccc","yyy","aaa"}我希望将IComparer接口用作:
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?发布于 2015-01-22 04:47:17
您知道要比较的值域吗?也就是说,您是否知道它们将是"ccc“、"yyy”和"aaa“(或者可能是其他值,但所有可能的值都是预先知道的)?
如果答案是肯定的,那么我会考虑使用一个字典,其中键是您已知值,值代表顺序。然后,在比较实现中,检索每个输入字符串的值并返回比较结果。
请原谅我可怜的VB,因为我不使用VB.Net,我也不想只发布一个C#版本。我想你能明白我的意思。实际上,您正在创建一个查找表,它将您的已知字符串映射到每个字符串的“序数”值(或它在所有已知字符串集中的位置)。在比较MyClass的过程中,从被比较的两个MyClass实例中获取Prop1的值(因为它看起来像您想要比较的值)。通过在字典中查找字符串,将每个字符串值转换为Integer。然后,您可以从一个Integer中减去另一个Integer,以获得比较结果。
需要考虑的一些事情:
祝好运!
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 Classhttps://stackoverflow.com/questions/28075914
复制相似问题