LINQ for string StartsWith List <string>

时间:2015-08-03 15:30:16

标签: c# xml linq

我正在使用LINQ解析XDocument。我想检查其中一个XElements,其中“BusinessStructure”键是以List<string> filters中的一个字符串开头的。换句话说,让我说我有:

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

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

使用LINQ,我该如何做......

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

但是,我没有获取过滤器列表的第一个索引,而是想“循环”遍历列表中的所有值,并检查XElement值是否以它开头。这可能是使用LINQ还是我必须使用foreach

2 个答案:

答案 0 :(得分:6)

你可以做一个直接的LINQ解决方案,稍微修改你的查询:

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

或者您可以通过过滤器构建正则表达式:

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)

如果考虑性能,请尝试并测量两者。

答案 1 :(得分:-1)

我会那样做;

filters.Any(f => x.Element("BusinessStructure").Value.IndexOf(f)==0)
相关问题