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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With