为了账号安全,请及时绑定邮箱和手机立即绑定

在 List<Tuple<>>() 或 asp:ListView 中对由字符和数字组成的值进行排序

在 List<Tuple<>>() 或 asp:ListView 中对由字符和数字组成的值进行排序

C#
白衣非少年 2022-11-13 13:45:40
我有一个元组列表,我正在用一个文件夹的所有目录填充这个列表,并使用以下代码将它绑定到 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();例如找到的目录是125661000110模板文件以这种方式对 List 或 ListView 进行排序的最佳方法是什么?先感谢您。我需要对它们按以下顺序排序的目录进行排序:文件模板10125661001
查看完整描述

1 回答

?
临摹微笑

TA贡献1982条经验 获得超2个赞

您可以为此使用 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();



查看完整回答
反对 回复 2022-11-13
  • 1 回答
  • 0 关注
  • 495 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号