如何在 LINQ 中执行此查询?
考虑这个简短的片段:
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 清楚地表达这一点?
它是什么?
Consider this brief snippet:
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);
}
}
Is there a way to express this cleanly using LINQ?
What is it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一个简单的翻译是使用 < 将每个候选词覆盖在模式词上code>Zip 运算符。
如果您确实想专注于索引,可以使用
Range
运算符:编辑:
正如 David Neale 指出的,
Zip
运算符在 .NET 4.0 之前不可用。实现它微不足道然而你自己。A straightforward translation would be to overlay each candidate-word over the pattern-word using the
Zip
operator.If you really want to focus on the indices, you can use the
Range
operator:EDIT:
As David Neale points out, the
Zip
operator is not available before .NET 4.0. It's trivial to implement it yourself, however.另一种不使用 Zip 的方法:
Another way of doing this w/o Zip: