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

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

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

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest