2015-01-30 4 views
1

У меня есть список доменов и субдоменов, какСортировка поддоменов на основе доменов

abc.com 
def.com 
ijk.com 
pages.abc.com 
help.abc.com 
contactus.def.com 
help.def.com 

Мое требование, чтобы отсортировать этот список по доменам, таким образом, что конечный результат является

abc.com 
pages.abc.com 
help.abc.com 
def.com 
contactus.def.com 
ijk.com 

Как может Я достигаю этого в C#? Im новое для программирования на C#. Может ли кто-нибудь помочь?

ответ

1

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()); 
+0

Добавлен специальный случай, если вы не имеете отчетливый домены –

+0

Большое спасибо !!! Ваш код работал как шарм. – manu

0

это можно сделать так:

 List<string> list = new List<string>(); 
     list.Add("abc.com"); 
     list.Add("def.com"); 
     list.Add("ijk.com"); 
     list.Add("pages.abc.com"); 
     list.Add("help.abc.com"); 
     list.Add("contactus.def.com"); 
     list.Add("help.def.com"); 
     List<string> listRoot = new List<string>(); 
     List<string> listSub = new List<string>(); 
     foreach (string item in list) 
     { 
      string[] split = item.Split(new char[] {'.'}, StringSplitOptions.RemoveEmptyEntries); 
      if (split.Length == 2) 
      { 
       listRoot.Add(item); 
      } 
      else 
      { 
       listSub.Add(item); 
      } 
     } 
     listRoot.Sort(); 
     Dictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>(); 
     foreach (string root in listRoot) 
     { 
      List<string> listSubIntern = new List<string>(); 
      foreach (string item in listSub) 
      { 
       if (item.EndsWith(root, StringComparison.InvariantCultureIgnoreCase)) 
       { 
        listSubIntern.Add(item); 
       } 
      } 
      listSubIntern.Sort(); 
      dictionary.Add(root, listSubIntern); 
     } 
     foreach (KeyValuePair<string, List<string>> keyValuePair in dictionary) 
     { 
      Console.WriteLine(keyValuePair.Key); 
      foreach (string s in keyValuePair.Value) 
      { 
       Console.WriteLine("\t{0}", s); 
      } 
     } 

и выход:

abc.com 
    help.abc.com 
    pages.abc.com 
def.com 
    contactus.def.com 
    help.def.com 
ijk.com 
1

Если вам нужно только отсортировать домен второго уровня & TLD, вы можете сделать что-то вроде этого.

var uriList = new string[] {"abc.com", "def.com", "ijk.com", "pages.abc.com", 
    "help.abc.com", "contactus.def.com", "help.def.com"}; 
var query = from uri in uriList.Select(item => 
    new { Uri = item, UriParts = item.Split('.') }) 
    orderby uri.UriParts[uri.UriParts.Length-2] + uri.UriParts[uri.UriParts.Length-1], 
    string.Join(".", uri.UriParts) select uri.Uri; 

Console.WriteLine(string.Join(" ,", query)); 

Выход будет немного отличаться от того, что вы ожидаете, например.

abc.com, help.abc.com, pages.abc.com, contactus.def.com, def.com, help.def.com, ijk.com

Смежные вопросы