2013-06-04 89 views
0

網址,我想使這個:C#名單及排序按文件名

anywhere.com/file/mybirthday.avi 
anywhere.com/file/yourbirthday.avi 
somewhere.com/file/mybirthday.avi 
somewhere.com/file/yourbirthday.avi 

這樣:

anywhere.com/file/mybirthday.avi 
somewhere.com/file/mybirthday.avi 
############## 
anywhere.com/file/yourbirthday.avi 
somewhere.com/file/yourbirthday.avi 

我發現了正則表達式的文件名。我把它們分類。所以我的代碼在這裏:

private void button1_Click(object sender, EventArgs e) 
{ 
    string gelenler = textBox2.Text; 
    gelenler = gelenler.Replace("\r\n\r\n", "\r\n"); 
    string cikti = string.Empty; 
    string regex = @"([^\/\\]+\.\w+)$"; 
    string[] parca = Regex.Split(gelenler, "\r\n"); 
    string[] parca2 = new string[parca.Length]; 
    for (int i = 0; i < parca.Length; i++) 
    { 
     string ad = match(regex, parca[i]); 
     parca2[i] = ad; 
    } 
    Array.Sort(parca2); 

    for (int j = 0; j < parca2.Length; j++) 
    { 
     for (int i = 0; i < parca2.Length; i++) 
     { 
      if (parca2[i].IndexOf(match(regex,parca[j]))!=-1) 
      { 
       textBox1.Text += parca[i] + Environment.NewLine; 
       parca[i] = ""; 
      } 
      textBox1.Text += "#############" + Environment.NewLine; 
      } 

     } 
} 

private string match(string regex, string html, int i = 1) 
{ 
    return new Regex(regex, RegexOptions.Multiline).Match(html).Groups[i].Value.Trim(); 
} 

但沒有工作。有任何想法嗎 ?

//對不起我的英語

+0

什麼時候/您想如何打印「##############」? – aquaraga

+0

Filename1.avi Filename1.avi Filename1.avi ############## Filename2.avi Filename2.avi Filename2.avi – user2451612

+0

你可以查我已經發布的代碼 - 你打算根據文件名進行分組嗎? – aquaraga

回答

2

我覺得永遠是最好的辦法是在這種情況下Path.GetFileName使用現有的.NET框架的東西,如:

 var strings = new[] 
         { 
          "anywhere.com/file/mybirthday.avi", 
          "anywhere.com/file/yourbirthday.avi", 
          "somewhere.com/file/mybirthday.avi", 
          "somewhere.com/file/yourbirthday.avi" 
         }; 

     strings = strings.OrderBy(x => Path.GetFileName(x)).ToArray(); 

     foreach (var s in strings) 
     { 
      Console.WriteLine(s);     
     } 

     Console.ReadKey(); 
+0

非常感謝,它的工作原理。 – user2451612

0

您應該使用Uri類。使用Segements屬性來獲取文件名(它將是最後一個段)。

var uris = new[] 
{ 
    new Uri("http://anywhere.com/file/mybirthday.avi"), 
    new Uri("http://anywhere.com/file/yourbirthday.avi"), 
    new Uri("http://somewhere.com/file/mybirthday.avi"), 
    new Uri("http://somewhere.com/file/yourbirthday.avi") 
}; 

var filename = uris.OrderBy(x => x.Segments[x.Segments.Length - 1]).ToArray(); 
foreach (var f in filename) 
{ 
    Console.WriteLine(f); 
} 
0

我想你是指分組文件;在這種情況下,可以使用以下代碼:

 IEnumerable<IGrouping<string, string>> groups = strings.GroupBy(x => Path.GetFileName(x)).OrderBy(g => g.Key); 
     foreach (var group in groups) 
     { 
      foreach (var str in group) 
      { 
       Console.WriteLine(str); 
      } 
      Console.WriteLine("#############"); 
     } 
+0

非常感謝。我確實合併了** Giedrius **和你的代碼。它的工作。 //再次抱歉我的英語:) – user2451612