LINQ for string StartsWith some value in List <string>

I am parsing XDocument using LINQ. I want to check if one of the XElements with key "BusinessStructure" is working with one of the lines in mine 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 would I then do something like ...

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

      

But instead of getting the first index of the filter list, I want to loop over all the values ​​in the list and check if the XElement starts with it. Is this possible with LINQ or do I need to do it with foreach

?

+3


source to share


2 answers


You can make a direct LINQ solution by slightly modifying your query:

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

      

Or you can create a regular expression 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 measuring both.

+6


source


I would do something like this;



filters.Any(f => x.Element("BusinessStructure").Value.IndexOf(f)==0)

      

-1


source







All Articles