How to specify to Regex (in a LINQ Query) to only compare the start of a string?
I have the following code:
string filterTerm = txtDocFilterTerm.Text.ToLower();
var regEx = new Regex(filterTerm);
//griQualifiedDocs is a grid
//storage.QualifiedDocs is the master/original collection
griQualifiedDocs.ItemsSource = storage.QualifiedDocs
.Where(item => regEx.IsMatch(item.DocName.ToLower()))
.ToList();
This query will return all of the strings that match the filterterm, regardless of it's place in the string. How can I restrict it so the regex is only run against the start of the string?
For example, the current code will return "Joe Jones" and "J开发者_运维百科onesy Smith" if the filter is "Jones"; I only want to return "Jonesy Smith"
TIA.
Use "^" to anchor to the start of a string.
var regEx = new Regex("^" + filterTerm);
Why not use this (assuming of course you're not passing in regex expressions):
griQualifiedDocs.ItemsSource = storage.QualifiedDocs
.Where(item =>item.DocName.ToLower().StartsWith(filterTerm))
.ToList();
精彩评论