简体   繁体   English

如何在 LINQ 中执行此查询?

[英]How to perform this query in 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?有没有办法使用 LINQ 干净地表达这一点?
What is it?它是什么?

A straightforward translation would be to overlay each candidate-word over the pattern-word using the Zip operator.一个简单的翻译是使用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;

If you really want to focus on the indices, you can use the Range operator:如果您真的想专注于索引,可以使用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;

EDIT:编辑:

As David Neale points out, the Zip operator is not available before .NET 4.0.正如 David Neale 指出的那样, Zip运算符在 .NET 4.0 之前不可用。 It's trivial to implement it yourself, however.然而,自己实现它是微不足道的。

Another way of doing this w/o Zip:不带 Zip 的另一种方法:

var possibleWords = candidateWords.Where(w => w.Length == pattern.Length && 
                                         word.Select((c, i) => pattern[i] == '_' || 
                                                               pattern[i] == c)
                                             .All(b => b))
                                  .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM