我有一个元组列表,并且用文件夹的所有目录填充此列表,并使用以下代码将其绑定到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();
例如找到的目录是
以这种方式对List或ListView进行排序的最佳方法是什么?先感谢您。 我需要按以下顺序对目录进行排序:
答案 0 :(得分:1)
您可以为此使用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();