考虑以下代码(虽然有点做作,但它是对现实世界程序的主要简化):
string[] strings = { "ab", "abcd", "abc", "ac", "b", "abcde", "c", "bc" };
string[] filters = { "a", "b", "c" };
// iteratively apply each filter
IEnumerable<string> filteredStrings = strings.ToArray();
foreach (string filter in filters)
{
// in my real-world program lots of processing and stuff
// happens here, hence why i need the enclosing foreach loop
filteredStrings = filteredStrings.Where(s => s.Contains(filter));
}
如您所见,代码迭代地将字符串数组过滤为较小的字符串集。当 for-each 循环完成时,filteredStrings
应该是通过所有过滤器的字符串子集。在这个例子中,这将是:
{ "abcd", "abc", "abcde" }
但是,我得到的输出是:
{ "abcd", "abc", "ac", "abcde", "c", "bc" }
它似乎只是过滤掉那些不包含的字符串"c"
,我认为这与它是最后一个过滤器有关。我想我一定没有以IEnumerable.Where()
正确的方式链接。这里发生了什么,我怎样才能得到正确的输出?
是的,根据我的代码中的注释,该 foreach 循环需要保持不变。