Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex in Linq statement?

I'm writing a short C# to parse a given XML file. But 1 of the tag values can change, but always includes words "Fast Start up" (disregarding case and spaces, but needs to be in the same order) in the where clause. I'm not sure how I would do this in a sql like statement in C#.

var selected = from cli in doc.Descendants(xmlns+ "Result")
     where cli.Element(xmlns + "ResultsLocation").Value == "Assessments-Fast-Startup"
                       select cli;
like image 285
jerryh91 Avatar asked Jun 04 '13 16:06

jerryh91


2 Answers

Assuming you are looking for the exact string - can you just use a String.Contains ?

var selected = from cli in doc.Descendants(xmlns+ "Result")
     where cli.Element(xmlns + "ResultsLocation").Value.Contains("Assessments-Fast-Startup")
     select cli;

Otherwise, something like:

var rx = new Regex("fast(.*?)startup", RegexOptions.IgnoreCase);

var selected = from cli in doc.Descendants(xmlns+ "Result")
    where rx.IsMatch(cli.Element(xmlns + "ResultsLocation").Value)
    select cli;
like image 175
Dave Bish Avatar answered Oct 19 '22 20:10

Dave Bish


a regex of fast[- ]?start[- ]?up should work

where an optional dash or space could be separating the word parts

...
where Regex.IsMatch(
    cli.Element(xmlns + "ResultsLocation").Value, 
    "fast[- ]?start[- ]?up", 
    RegexOptions.IgnoreCase
)
select cli

if you find you need to tweak the regex try a regex tester like http://regexpal.com/

As @DaveBish has mentioned you might be fine with .Contains(...) test instead of a regex or even .ToLower().Contains(...) chaining (you may also need a null check as well)

like image 35
MikeM Avatar answered Oct 19 '22 21:10

MikeM