用字符串实现自定义IComparer [英] Implementing custom IComparer with string
本文介绍了用字符串实现自定义IComparer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我在c#中有一个字符串集合;
I have a collection of strings in c#, for example;
var example = new string[]{"c", "b", "a", "d"};
然后我用它来对此进行排序,但是我的IComparer方法不起作用,并且根据事物的外观无限循环.
I then with to sort this, but my IComparer method is not working, and looping infinitely by the seems of things.
基本上,我需要先进入"b"
,然后是"c"
,然后我才不在乎其他任何人的顺序.
Basically I need "b"
to come first, followed by "c"
, then I dont care about the order of any of the others.
使用I Comparer<string>
和Compare(string x, string y)
方法可以吗?
Is this possible using IComparer<string>
and the Compare(string x, string y)
method?
代码
public int Compare(string x, string y)
{
var sOrder = new string[] { "b", "c" };
int index_x = -1;
int index_y = -1;
for (int i = 0; i < sOrder.Length;i++)
{
if (sOrder[i] == x)
index_x = i;
else if (sOrder[i] == y)
index_y = i;
}
if (index_x >= 0 && index_y >= 0)
{
if (index_x < index_y)
{
return -1;
}
else
return 1;
}
return 0;
}
推荐答案
这应该做您想要的:
var example = new string[]{"c", "a", "d", "b"};
var comparer = new CustomStringComparer(StringComparer.CurrentCulture);
Array.Sort(example, comparer);
...
class CustomStringComparer : IComparer<string>
{
private readonly IComparer<string> _baseComparer;
public CustomStringComparer(IComparer<string> baseComparer)
{
_baseComparer = baseComparer;
}
public int Compare(string x, string y)
{
if (_baseComparer.Compare(x, y) == 0)
return 0;
// "b" comes before everything else
if (_baseComparer.Compare(x, "b") == 0)
return -1;
if (_baseComparer.Compare(y, "b") == 0)
return 1;
// "c" comes next
if (_baseComparer.Compare(x, "c") == 0)
return -1;
if (_baseComparer.Compare(y, "c") == 0)
return 1;
return _baseComparer.Compare(x, y);
}
}
这篇关于用字符串实现自定义IComparer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文