我有一个.sql文件目录字符串数组,我需要按升序排序。实际上我想基于数字部分对它进行排序,如果没有数字部分那么文件应该在顶部。 我怎么能这样做?
3.5.1_Patch
3.5_CoreScript
3.6_Patch
3.6.1_Patch
答案 0 :(得分:-1)
你应该尽可能具体地提出问题。您可以使用Array.Sort
和lambda函数执行所需操作:
string [] files = new string[] {"3.6.1_Patch","3.5_CoreScript","3.5.1_Patch","3.6_Patch"};
Array.Sort(files, (x,y) => {
string [] x1 = x.Split('_');
string [] y1 = y.Split('_');
return String.Compare(x1[0], y1[0]);
});
我把它留给你来处理没有版本号的边缘情况。
修改强>
您的文件名比最初提供的文件更复杂。我假设第一个非数字字符串的所有内容都是版本?
此时我会创建一个类来解析文件名并存储版本号。它还实现了用于排序的IComparable
接口。
public class Version : IComparable<Version> {
// Just guessing here - without knowing the actual format
public int Major = 0;
public int Minor = 0;
public int Build = 0;
public string FileName;
public Version(string fileName) {
ParseFileName(fileName);
}
// Split the string on '_' or '.',
// Considers the first 3 numbers to be version
// (stops parsing at non-numeric value)
public void ParseFileName(string fileName)
{
FileName = fileName;
string [] data = Regex.Split(fileName, @"[_\.]");
int x;
if (Int32.TryParse(data[0], out x)) {
Major = x;
if (2 <= data.Length && Int32.TryParse(data[1], out x)) {
Minor = x;
if (3 <= data.Length && Int32.TryParse(data[2], out x)) {
Build = x;
}
}
}
}
public override string ToString() {
return FileName;
}
// Comparison
public int CompareTo(Version v) {
int c = Major.CompareTo(v.Major);
if (0 == c) {
c = Minor.CompareTo(v.Minor);
}
if (0 == c) {
c = Build.CompareTo(v.Build);
}
return c;
}
}
测试程序:
string [] files = new string[] {"10.6.1_Patch","3.5_CoreScript","3.5.1_Patch","3.6_Patch","10.6_Patch", "test", "01_1_ALTER_TC_EDB_V3", "01_2_ALTER_TC_EDB_V3"};
Version [] versions = new Version[files.Length];
for (int i = 0; i < files.Length; i++) {
versions[i] = new Version(files[i]);
}
Array.Sort(versions);
foreach (var v in versions) {
Console.WriteLine(v.ToString());
}
输出:
test
01_1_ALTER_TC_EDB_V3
01_2_ALTER_TC_EDB_V3
3.5_CoreScript
3.5.1_Patch
3.6_Patch
10.6_Patch
10.6.1_Patch
答案 1 :(得分:-1)
试试这个:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication34
{
class Program
{
static void Main(string[] args)
{
List<string> input = new List<string>() { "3.5.1_Patch", "3.5_CoreScript", "3.6_Patch", "3.6.1_Patch" };
input.Sort((x,y) => new CustomSort() { s = x}.CompareTo(y));
}
}
public class CustomSort : IComparable
{
public string s { get; set; }
public int CompareTo(object input)
{
string[] thissplitArray = (s).Split(new char[] { '_' }).ToArray();
string[] splitArray = ((string)input).Split(new char[] { '_' }).ToArray();
if (thissplitArray[0] == splitArray[0])
{
return thissplitArray[1].CompareTo(splitArray[1]);
}
else
{
return thissplitArray[0].CompareTo(splitArray[0]);
}
}
}
}