Think вы сделали ошибку сортировки пример, но вот решение:
class DomainComparer : IComparer<string>
{
public int Compare(string x, string y)
{
if(x==y) return 0;
string[] _x = x.Split('.');
string[] _y = y.Split('.');
return Compare(_x, _y, 0);
}
private int Compare(string[] x, string[] y, int depth)
{
if (x.Length - depth - 1 >= 0 && y.Length - depth -1 < 0)
{
return +1;
}
if (y.Length - depth - 1 >= 0 && x.Length - depth -1 < 0)
{
return -1;
}
if (x[x.Length-depth-1].CompareTo(y[y.Length - depth-1]) == 0)
{
return Compare(x, y, depth + 1);
}
else
{
return x[x.Length-depth-1].CompareTo(y[y.Length - depth-1]);
}
}
}
Тогда вы можете позвонить ему с:
string[] domains = new[] { "abc.com", "def.com", "ijk.com", "pages.abc.com", "help.abc.com", "contactus.def.com", "help.def.com" };
Array.Sort(domains, new DomainComparer());
foreach (var item in domains)
{
Console.WriteLine(item);
}
Выход:
abc.com
help.abc.com
pages.abc.com
def.com
contactus.def.com
help.def.com
ijk.com
Или, если вы не имеете массив, но
List<string>
или
IEnumerable<string>
вы можете сделать это с Linq:
IEnumerable<string> sorted = domains.OrderBy(x => x, new DomainComparer());
Добавлен специальный случай, если вы не имеете отчетливый домены –
Большое спасибо !!! Ваш код работал как шарм. – manu