考虑这个简短的片段:
var candidateWords = GetScrabblePossibilities(letters);
var possibleWords = new List<String>();
foreach (var word in candidateWords)
{
if (word.Length == pattern.Length)
{
bool goodMatch = true;
for (int i=0; i < pattern.Length && goodMatch; i++)
{
var c = pattern[i];
if (c!='_' && word[i]!=c)
goodMatch = false;
}
if (goodMatch)
possibleWords.Add(word);
}
}
是否有一种方法来表达这干净使用LINQ?
这是什么?
一种简单的翻译是使用Zip
运算符将每个候选词覆盖在模式词上。
var possibleWords = from word in candidateWords
where word.Length == pattern.Length
&& word.Zip(pattern, (wc, pc) => pc == '_' || wc == pc)
.All(match => match)
select word;
如果你真的想关注索引,你可以使用Range
操作符:
var possibleWords = from word in candidateWords
where word.Length == pattern.Length
&& Enumerable.Range(0, word.Length)
.All(i => pattern[i] == '_'
|| pattern[i] == word[i])
select word;
编辑:正如David Neale指出的,Zip
操作符在。net 4.0之前是不可用的。但是,自己实现它是微不足道的。
另一种方法:
var possibleWords = candidateWords.Where(w => w.Length == pattern.Length &&
word.Select((c, i) => pattern[i] == '_' ||
pattern[i] == c)
.All(b => b))
.ToList();