2011-11-23 87 views

回答

11

爲什麼要使用正則表達式?他們不執行比較。然而,不僅System.Version將解析字符串,但它支持的比較:

// Use your favorite comparison operator 
var current = new Version("4.0.1.2"); 
var found = new Version("4.0.1.0"); 
if (found > current) 
{ 
    Console.WriteLine("Upgrade needed to {0} from {1}", found, current); 
} 
else 
{ 
    Console.WriteLine("No upgraded needed from {0}", current); 
} 

或者,如果你在一個枚舉有他們,它很好地使用LINQ:

var versions = new [] { "3.0.0.0", "3.1.0.0", "4.0.1.0", "4.0.1.2" }; 
foreach (var version in versions.Select(Version.Parse) 
           .OrderByDescending(v => v)) 
{ 
    Console.WriteLine("{0}", version); 
} 

// Group them by Major Version first, then sort 
foreach (var major in versions.Select(Version.Parse) 
           .GroupBy(v => v.Major) 
           .OrderByDescending(g => g.Key)) 
{ 
    Console.WriteLine("{0}: {1}", 
         major.Key, 
         String.Join(", ", major.OrderByDescending(v => v))); 
} 
0

嘗試與這一個

static class Program 

{ 

static void Main() 

{ 

string v1 = "1.23.56.1487"; 
string v2 = "1.24.55.487"; 

var version1 = new Version(v1); 
var version2 = new Version(v2); 

var result = version1.CompareTo(version2); 
    if (result > 0) 
     Console.WriteLine("version1 is greater"); 
    else if (result < 0) 
     Console.WriteLine("version2 is greater"); 
    else 
     Console.WriteLine("versions are equal"); 
    return; 

} 

}

-4

那麼版本號只是一個數字..比較3.0.0.0 & 3.1.0.0就像比較3000和3100一樣最簡單的是:

int v1 = 3000; 
int v2 = 3100; 

if (v2 > v1) { my routine; } 
+0

除版本爲4.0.30319.1(當前C#編譯器的版本號)外。 – user7116

+0

你沒有提及與同一主要版本編號比較不同的版本!!!!!! –