开发者

Partial Matching an ObservableCollection<string> Object

开发者 https://www.devze.com 2023-01-21 13:34 出处:网络
Ok let\'s say I have an ObservableCollection<string> object. Within this object I have a variety of strings:

Ok let's say I have an ObservableCollection<string> object. Within this object I have a variety of strings:

SomeString01
SomeString-02
somestring-03
SOMESTRING.04
aString

I want to take an input, we'll call it pattern and store it as a string from a User interface, and do some partial matching on the ObservableCollection. I need do to partial matching on the collection, and everything is going to be case insensitive. In the end I want to these compiled into a brand new ObservableCollection. So here are some example cases:

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
So开发者_开发技巧meString-02
somestring-03
SOMESTRING.04
aString

What is the best approach for this in a ClickOnce application?


Like Gabes answer in the comments.

but slightly more specific

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


Ok I actually dug around more with Google, and found a better solution:

You could use IndexOf() and pass StringComparison.OrdinalIgnoreCase

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

Even better is defining a new extension method for string:

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);

Contributed by: JaredPar

Source: Case insensitive 'Contains(string)'


SO now I have implemented it in my source as follows:

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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消