2010-10-21 88 views
1

好吧,假設我有一個ObservableCollection<string>對象。在這個目標我有各種各樣的字符串:部分匹配ObservableCollection <string>對象

SomeString01 
SomeString-02 
somestring-03 
SOMESTRING.04 
aString 

我要帶一個輸入,我們把它叫做pattern並將其存儲爲從用戶界面的字符串,並且做對ObservableCollection一些部分匹配。我需要做的集合上的部分匹配,並且一切都將是案件不敏感。最後我想把這些編入一個全新的ObservableCollection。因此,這裏有一些例子情況:

pattern = "SoME" 

// RESULTS: 
SomeString01 
SomeString-02 
somestring-03 
SOMESTRING.04 

/* --- */ 

pattern = "-0" 

// RESULTS: 
SomeString-02 
somestring-03 

/* --- */ 

pattern = "ING0" 

// RESULTS: 
SomeString01 

pattern = "s" 

// RESULTS: 
SomeString01 
SomeString-02 
somestring-03 
SOMESTRING.04 
aString 

,這是什麼在ClickOnce應用程序的最佳方法?

+2

你不能在收集使用'。凡(X =>)'? – 2010-10-21 14:37:19

+0

...你的問題是? – TalentTuner 2010-10-21 14:38:11

+0

@saurabh ...在集合上執行不區分大小寫部分匹配的最佳方法是什麼?我做了一個糟糕的工作,說明我的問題? – Urda 2010-10-21 14:41:14

回答

0

好吧,我其實與谷歌挖得越多,發現一個更好的解決方案:

你可以使用的IndexOf(),並通過StringComparison.OrdinalIgnoreCase

string title = "STRING"; 
bool contains = title.IndexOf("string", StringComparison.OrdinalIgnoreCase) >= 0; 

更妙的是定義一個新的擴展方法字符串:

public static bool Contains(this string source, string toCheck, StringComparison comp) 
{ 
    return source.IndexOf(toCheck, comp) >= 0; 
} 

string title = "STRING"; 
bool contains = title.Contains("string", StringComparison.OrdinalIgnoreCase); 

供稿人:JaredPar

來源:Case insensitive 'Contains(string)'


所以現在我已經在我的源代碼如下實現它:

foreach (string source in SourceStrings) 
{ 
    // Code for some pre-reqs here 

    if (source.IndexOf(Pattern, StringComparison.OrdinalIgnoreCase) >= 0) 
    { 
     subset.Add(source); 
    } 

    // Finish up anything else I had to do here 
} 
1

像加貝斯答案的評論。

但是稍微更具體的

.Where(x => x.IndexOf("Some",StringComparison.InvariantCultureIgnoreCase) != -1) 
+0

什麼是使用與'。凡(X => x.IndexOf(圖案,StringComparison.OrdinalIgnoreCase> = 0)'或者這6的一種方式,半打其他 – Urda 2010-10-21 14:59:59

+0

HTTP的區別:?// stackoverflow.com/questions/492799/difference-between-invariantculture-and-ordinal-string-comparision是一個很好的寫法..我不知道如何張貼鏈接的評論,但仍然有效。很多6個單向,半打另一個 – 2010-10-21 16:11:56