代码之家  ›  专栏  ›  技术社区  ›  raven_977

对由列表中的字符和数字组成的值进行排序

  •  0
  • raven_977  · 技术社区  · 5 年前

    我有一个元组列表,我正在用文件夹的所有目录填充此列表,并用以下代码将其绑定到asp:ListView:

    List<string> directoryContent = new List<string>(Directory.GetFileSystemEntries(dirPath);
    List<Tuple<string, string>> directoryList = new List<Tuple<string, string>>();
    
    for (int i = 0; i < directoryContent.Count; i++)
    {
        FileAttributes attr = File.GetAttributes(directoryContent[i]);
        if (attr.ToString().Equals("Directory"))
        {
            String str = directoryContent[i].Remove(0, dirPath.Length);
            string count = Directory.GetFiles(directoryContent[i], "*.*", SearchOption.AllDirectories).Length.ToString();
            directoryList.Add(new Tuple<string, string>(str, count));
        }
    }
    
    directoryListView.DataSource = directoryList;
    directoryListView.DataBind();
    

    例如,找到的目录是

    • 566个
    • 10001个
    • 10个
    • 文件夹

    以这种方式对列表或列表视图进行排序的最佳方法是什么?提前谢谢你。

    • 文件夹
    • 模板
    • 德意志北方银行
    • 1001个
    0 回复  |  直到 5 年前
        1
  •  1
  •   VDWWD    5 年前

    你可以用Linq来做。

    //test data
    List<string> list = new List<string>()
    {
        "12",
        "566",
        "10001",
        "10",
        "templates",
        "files"
    };
    
    int tempInt;
    
    //filter the numbers from the list and sort
    var listNumbers = list.Where(x => int.TryParse(x, out tempInt)).Select(y => Convert.ToInt32(y)).OrderBy(z => z);
    
    //filter the strings from the list and sort
    var listStrings = list.Where(x => !int.TryParse(x, out tempInt)).OrderBy(y => y);
    
    //join the two lists again
    var orderedList = listStrings.Concat(listNumbers.Select(y => y.ToString())).ToList();
    

    List<Tuple<string, string>> list = new List<Tuple<string, string>>()
    {
        new Tuple<string, string>("12", "NA"),
        new Tuple<string, string>("566", "NA"),
        new Tuple<string, string>("10001", "NA"),
        new Tuple<string, string>("10", "NA"),
        new Tuple<string, string>("templates", "NA"),
        new Tuple<string, string>("files", "NA")
    };
    
    int tempInt;
    
    //filter the numbers from the list and sort
    var listNumbers = list.Where(x => int.TryParse(x.Item1, out tempInt)).Select(y => new Tuple<int, string>(Convert.ToInt32(y.Item1), y.Item2)).OrderBy(z => z.Item1);
    
    //filter the strings from the list and sort
    var listStrings = list.Where(x => !int.TryParse(x.Item1, out tempInt)).OrderBy(z => z.Item1);
    
    //join the two lists again
    var orderedList = listStrings.Concat(listNumbers.Select(y => new Tuple<string, string>(y.Item1.ToString(), y.Item2))).ToList();