Regex in Linq statement?

jerryh91 picture jerryh91 · Jun 4, 2013 · Viewed 28.2k times · Source

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;

Answer

Dave Bish picture Dave Bish · Jun 4, 2013

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;