Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ for string StartsWith some value in List<string>

Tags:

c#

xml

linq

I'm parsing an XDocument using LINQ. I want to check if one of the XElements, with key "BusinessStructure" starts with one of the strings in my List<string> filters. In other words, let's say I have:

x.Element("BusinessStructure").Value = "testing123"

and

var filters = new List<string> {"test", "hello"}

Using LINQ, how do I then do something like...

...
where x.Element("BusinessStructure").Value.StartsWith(filters[0])
select new...

But instead of getting the first index of the filters list, I want to "loop" through all the values in the list and check if the XElement value starts with it. Is this possible using LINQ or do I have to do it using a foreach?

like image 852
illya Avatar asked Feb 09 '23 09:02

illya


1 Answers

You could do a straight LINQ solution, modifying your query slightly:

let bs = x.Element("BusinessStructure")
where bs != null && filters.Any(f => bs.Value.StartsWith(f))

Or you could build a regex from your filters:

var prefixRegex = new Regex("\\A" + string.Join("|",filters.Select(f=>Regex.Escape(f)));
...
let bs = x.Element("BusinessStructure")
where bs != null && prefixRegex.IsMatch(bs.Value)

If performance is a consideration, try and measure both.

like image 115
Jerry Federspiel Avatar answered Feb 11 '23 23:02

Jerry Federspiel