C#List&按FileName对URL排序

时间:2013-06-04 12:12:12

标签: c# regex sorting uri hyperlink

我想这样做:

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

To This:

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

但没有奏效。有什么想法吗?

//对不起我的英文

3 个答案:

答案 0 :(得分:2)

我认为最好的想法是使用现有的.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();

答案 1 :(得分: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);
}

答案 2 :(得分: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("#############");
        }