c# List &按文件名排序url

本文关键字:排序 url 文件名 List | 更新日期: 2023-09-27 18:16:46

我想让这个:

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();
}

但是不起作用。有什么想法吗?

//Sorry my English

c# List &按文件名排序url

我认为最好的办法是使用现有的。net框架的东西,在这种情况下,Path.GetFileName:

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

我想你的意思是把文件分组;在这种情况下,可以使用以下代码:

        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("#############");
        }

您应该使用Uri类。使用segments属性来获取文件名(它将是最后一个片段)。

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);
}